+ 1
Python question
Why does the following: def func(x): res = 0 for i in range(x): res += i return res Print(func(4)) result in 6. I thought it was 4. Can someone explain?
3 odpowiedzi
+ 5
range(4) => 0,1,2,3
0 + 1 + 2 + 3 = 6
Step by step (Loop)
1) res = 0 + 0 #res = 0
2) res = 0 + 1 #res = 1
3) res = 1 + 2 #res = 3
4) res = 3 + 3 #res = 6
+ 1
Thank you so much! I really appreciate it
+ 1
You are welcome