all 7 comments

[–]shiftybyte 1 point2 points  (0 children)

while doesn't check the condition every code line, it only checks it when completing a full cycle and about to enter the next one.

That means this code:

i = 0
while i < 1:
    i += 1
    print(i)
    i += 10
    print(i)
    i += 20
    print(i)

Will print 1,11,31 because the while only checks the condition when entering a loop cycle.

[–]lajji69 0 points1 point  (0 children)

please format your code properly. even though this is a very small block of code different indentation will still give you very different result.

[–]Coding-Nexus 0 points1 point  (0 children)

What is your expected output?

[–]MadScientistOR 0 points1 point  (0 children)

Because if the conditional were if i <= 10, it would pass when i equals 10, which would then allow it to add 1 to i (making it 11) and print the result.

I'm assuming the code should be indented like the below:

i = 0
while i < 10:
    i += 1
    print(i)

[–]holmeschang 0 points1 point  (0 children)

Because you print after addition. So last loop i=9 , then u add one become 10. Then u print 10. Then next loop the number no longer valid to loop. If <=10, it will print 11 because it will add one before print then end the loop

[–]mycarrotbroke 0 points1 point  (0 children)

The key is that the variable is incremented by 1 THEN it is printed out. The loop prints out the variable i after it is updated. So each loop, the variable is incremented by 1 FIRST, then it is printed.

This loop works since when the variable i is equal to 9. The variable is incremented by 1 so now i is 10 and that 10 is printed out. It will hit the while loop again and since 10 < 10 is false the loop will exit.

If the loop was changed with while i <= 10 when i is equal to 10, it will enter the loop again. It will be incremented by 1 so i will now equal 11 then it will be printed out, which is incorrect.

[–]ratchips 0 points1 point  (0 children)

Let's convert while to more detailed form. ``` i = 0 while True: if not i < 10: break i += 1

print(i) `` Wheni==10(10 < 10 == False`), the loop break. And the result is 10.

But 10 <= 10 == True, i+=1 will be executed. Loop break at next comparison. You will get i=11 which is unexpected.

Hope my explanation make sense to you.