← Intro to programming with Python

while loops

Repeat while a condition stays True.

Start this lesson

Computers are great at doing the same thing many times without getting bored. A while loop repeats its indented lines as long as its condition is True. Each time round, Python checks the condition again; the moment it is False, the loop ends and the program carries on below. Something inside the loop must change, or the condition stays True forever.

countdown = 3
while countdown > 0:
    print(countdown)
    countdown -= 1
print("Lift off!")

This shows 3, 2, 1 and then Lift off!. After printing 1, countdown becomes 0, the condition 0 > 0 is False, and the loop stops.

Common mistake: forgetting to change the variable. Without countdown -= 1 the condition is always True and the loop never ends (an "infinite loop"). If that happens, stop the program and look for the missing update.

while is the right choice when you do not know in advance how many times to repeat, for example "keep asking until the answer is right".

break jumps out of a loop straight away, even if the condition is still True.