Pulsars
0 %
Log inSign up

Loops

The while loop and classic pitfalls

The while loop and classic pitfalls

Unlike for, the while loop repeats a block of instructions as long as a condition remains true, without knowing in advance the number of repetitions.

compteur = 5
while compteur > 0:
    print(compteur)
    compteur = compteur - 1
print("Liftoff!")

This program displays 5, 4, 3, 2, 1, then Liftoff!. Each time through the loop, Python first checks the condition compteur > 0: if it is true, it executes the block, then goes back to check the condition. As soon as it becomes false, the loop stops.

The classic infinite loop mistake: if you forget to modify the variable tested in the condition, it stays true forever, and the loop never stops.

compteur = 5
while compteur > 0:
    print(compteur)
    # (Forgotten: compteur is never decreased)

Here, compteur remains eternally equal to 5, the condition compteur > 0 is always true, and the program runs indefinitely (you have to stop it manually!). Always check that the condition of your while loop will eventually become false.

The classic indentation mistake: in Python, only the lines indented under the while belong to the loop. If a line that should be repeated is not indented at the right level, it will be executed at the wrong time (only once, before or after the loop, instead of on every pass).

compteur = 3
while compteur > 0:
    compteur = compteur - 1
print(compteur)  # (badly indented: outside the loop, executed only once at the end)

In summary: use for when you know the number of repetitions in advance, and while when you repeat an action until a condition changes, always checking that this condition will eventually become false.