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))

12th Jun 2019, 8:35 PM
Nyaniba
Nyaniba - avatar
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".
13th Jun 2019, 4:18 AM
Luiz Felipe da Silva Valério
Luiz Felipe da Silva Valério - avatar
+ 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
12th Jun 2019, 8:45 PM
Anna
Anna - avatar
+ 2
Understood. Thank you
14th Jun 2019, 8:14 PM
Nyaniba
Nyaniba - avatar