0

# Why sometimes 0 is printed?

In phyton Why 0 is printed ? i = 0 while True:   print(i)   i = i + 1   if i >= 5:     print("Breaking")     break print("Finished") Why 0 is is not printing and why 5 was printed? i = 0 while i<5:   i += 1   if i==3:     print("Skipping 3")     continue   print(i)

1st Dec 2022, 4:20 AM
William A Cruz Mendoza + 1
i is set to 0 before the start of both cases. Both have i += 1 in each iteration. And both will stop when i == 5. So, both will iterate 5 times with i's starting value = 0, 1, 2, 3, 4. Thus, Case 1 prints i, that is, 0, 1, 2, 3, 4. Case 2 prints i+1, that is, 1, 2, 3, 4, 5. That's for the values of i. For the actual output, you will have to put things like skipping 3 back.
2nd Dec 2022, 5:29 AM
Lochard + 6
In the first case, you set i = 0 and it is printed before the i = i + 1 statement. In the second case, i is 4 in the last iteration, and i += 1 is executed before print(i).
1st Dec 2022, 4:41 AM
Lochard + 1
Let's compare the 2 cases. First, let's take the if i==3: block in case 2 out because it is not our concern in this matter. The while statements are checks, but while True will always be true so we can ignore it. The real check in case 1 is the if i >= 5: block. The checks in two cases are essentially the same because `(run) while i < 5` is the same as `if i >= 5: break`. So the 2 cases are essentially: Case 1: 1. print(i) 2. i +=1 3. check Case 2: 1. check 2. i += 1 3. print(i) Once loops started iterating, checking at the end and checking at the beginning are basically the same, since they won't cause a stop in the middle of the code block. That leaves our cases as: Case 1: First, print(i), then i += 1. In other words, it prints i's starting value of each iteration, let just call it "i". Case 2: First, i += 1, then print(i). In other words, it prints i's starting value of each iteration +1, that is "i+1".
2nd Dec 2022, 5:14 AM
Lochard 0
I still don't understand. How can I tell which one is setting to start from zero. Both have iterations
2nd Dec 2022, 2:52 AM
William A Cruz Mendoza 0
Thank you so much. I had so much trouble figuring this out. I appreciate it 🙏
2nd Dec 2022, 11:56 AM
William A Cruz Mendoza 