Why does the same while statement give different results? I'm a beginner, could someone explain this

Viewed 18

An example:

x = 5
while x > 0:
    print(x)
    x = x-1

This seems to output: 5 4 3 2 1. It doesn't print 0 which makes sense, as the while statement is supposed to run while the value of x is greater than 0.

But if I write the code as:

x = 5
while x > 0:
     x = x-1
     print(x)

This seems to output: 4 3 2 1 0, as I've set it to execute the expression first then print it which makes sense as well. But what I can't seem to figure out is that this time it prints 0 as well. Shouldn't the loop stop at 1 as it's supposed to run only while x is greater than 0? Why does it print the 0 too? Pardon my mistakes as I'm only learning.

1 Answers

The reason is that while loops check whether the condition is met, run the whole block, then check again after the block finishes, to see if the condition is still met, before running again.

So here, when x gets to 1 (i.e. x>0 is True), the condition is met, then it does the block

x=x-1   # x becomes zero
print(x)  # print zero

then it checks x>0, and this time the condition is not met (False), so the loop stops.

Related