Need help understanding this while loop

In case that is what is causing the confusion, the condition is not checked all the time, but only before the first statement in the loop. Therefore, if the value is incremented before the print statement, the condition will only be checked after the value is printed. If you think through the code, let’s suppose we have the above, just starting at a later number for brevity:

current_number = 5
while current_number <= 5:
    print(current_number)
    current_number += 1

current_number is <= 5, so the loop runs, 5 is printed and then current_number is incremented to 6. Now the condition is checked again, and as the condition 6 <= 6 is false, the loop terminates. By contrast, with

current_number = 5
while current_number <= 5:
    current_number += 1
    print(current_number)

…everything happens as before, except the number is incremented to 6 before the print, and thus 6 is printed.

These sort of off by one errors are particularly common with while loops if you’re not careful, which is one reason why in real life you’d always use a for loop for this sort of iteration, where you have a sequence of things and you want to iterate a fixed number of times:

for current_number in range(1, 6):
    print(current_number)

This is both shorter and avoids the above type of “off by one” errors due to the order of the action and the incrementing.

5 Likes