The while Loop

A while loop runs its block again and again, as long as its condition is true. Python checks the condition before each run of the loop. One run of a loop is called an iteration.

step = 1

while step <= 3:
    print("Step", step)
    step += 1

print("Done")

Output:

Step 1
Step 2
Step 3
Done

Each time through the loop, step += 1 adds 1 to step. After the third run, step is 4. Now step <= 3 is false, so the loop ends and Python moves on to print("Done").

Without the step += 1 line, step would stay 1. The condition would always be true, so the loop would never finish.

Use while when you know when the loop should stop, but not how many times it will run. When you know the exact number of repetitions, a for loop (next lesson) is usually clearer.

Finish the launch countdown in the exercise.