0
Explanation
Can someone explain why the code below outputs '6'? def fun(x): res = 0 for i in range(x): res += i return res print(func(4))
3 Respostas
+ 1
It is summing up. On the first loop, it will do res (that is 0) + i (that will also be zero) and the result will be zero. On the second loop, it will be 0 + 1, so res is now 1. On the third loop, it will be 1 + 2, and res will be 3. Finally, the forth loop does 3 + 3, and that is why res returns as 6.
If you want to count the loops instead of summing them up, you should write "res += 1" instead of "res += i".
+ 3
There's something wrong with your indentation. In its current format the code won't run
range(x) contains all numbers from 0 to x-1. The sum of all numbers from 0 to 3 is 6
+ 2
Understood. Thank you