Help.... Why does placement of variables affecting output? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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

27th Mar 2018, 2:39 PM
Tan Mu En
Tan Mu En - avatar
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
27th Mar 2018, 3:14 PM
Dan Walker
Dan Walker - avatar
0
I see... Thanks a lot!
27th Mar 2018, 3:17 PM
Tan Mu En
Tan Mu En - avatar