← All lessons

while: repeat while the condition holds

Sign in · Sign up

Lesson 3.0

while repeats code as long as the condition is true:

i = 3
while i > 0:
    print("Countdown", i)
    i -= 1

A loop has three parts: the line with the condition and a colon, the body with an indent, and the change of the counter i -= 1. Remove the last line and the condition i > 0 stays true forever, and the program hangs. Don't copy the example: you need to print different numbers.

Print the numbers from 1 to 5, each on a new line.

Hint

A while loop needs three parts: a starting value, a condition and the change of the counter at the end of the body.

Without i += 1 the condition i <= 5 stays true forever and the program hangs — the check stops it and tells you so.