0
Help.... Why does placement of variables affecting output?
Just started learning python. I'm so sorry if this question is asked before but why the 2 cases produced different results? Case 1: total = 0 for i in range(1, 5): total += i print(total) Output = 10 Case 2: for i in range(1, 5): total = 0 total +=i print(total) Output = 4
2 Answers
- 1
In the second case total is reset to 0 every time the loop runs, except the last time when you exit the loop, so it actually stores the last number you looped on, which was 4
0
I see...
Thanks a lot!