← Python lessons

While Loops

A while loop repeats its body while a condition is true. Python checks the condition before each repetition. If it is false at the first check, the body does not run at all.

The shape of a while loop

counter = 1
while counter <= 3:
    print(counter)
    counter = counter + 1
print("finished")

Python checks the condition before each repetition. When it is true, Python runs the indented body, then checks again. This program prints 1, 2 and 3 on separate lines, followed by finished.

After the third repetition, counter is 4. The next check is false, so Python continues after the loop. Changing a variable does not by itself skip the remaining statements in the current repetition.

The update makes progress toward the stopping condition. Without it, this example would keep printing 1. If the condition is false at the first check, the body runs zero times.

while or for?

Use for to visit items from an iterable, such as the values produced by range(10). Use while when repetition is controlled by a condition, such as whether the next multiple is below a limit. A known repeat count usually makes for the simpler choice, but while can also express counted repetition.

See also: For loops, break and continue, Comparisons and Logical Operators.

Your turn

Use a while loop to print the positive multiples of 3 that are less than 10. The first value is supplied. Increase it by 3 after printing it.

number = 3
# Add the loop here.

Expected output

3
6
9

Check the next value after 9: it is 12, so it must not be printed.


Practise this in the free Python course, where every exercise checks your code instantly.