+ 1

Can u please explain this code

def func(x): res = 0 for i in range(x): res += i return res print(func(4))

17th Jan 2019, 2:34 PM
Rangasube
Rangasube - avatar
3 Answers
+ 3
0+0+1+2+3 output 6 Oh no, return is in for loop So 0+0 Output 0 At first iteration, exit the function with return
17th Jan 2019, 2:45 PM
Gordon
Gordon - avatar
+ 2
The return statement seems to be wrongly indented, it should be on the level of for. If that is given: The last line calls the function func, passing 4 as an argument. The loop adds every value in 0, 1, 2, 3 (range(4)) to res, then res gets returned. Result: 6. With the mistake: Always 0.
17th Jan 2019, 2:47 PM
HonFu
HonFu - avatar
+ 2
It's not wrongly indented It's just a tricky quiz đŸ€Ł
17th Jan 2019, 2:50 PM
Gordon
Gordon - avatar