Python Arena
Step 1 of 4

A loop with a condition

In the last module, every loop started with while True:. Since True is always true, a loop like that would run forever on its own, so a break inside it did the stopping. But while can do more: like if, it takes any condition, and the loop runs as long as the condition is true.

Here is a loop in the style of the last module. It counts to three:

number = 1
while True:
    if number > 3:
        break
    print(number)
    number += 1
print("Done")
Output
1
2
3
Done

And here is the same loop with a condition:

number = 1
while number <= 3:
    print(number)
    number += 1
print("Done")
Output
1
2
3
Done

This is what Python does with it:

  1. It checks the condition number <= 3. If it's true, it runs the indented lines under the while, the body of the loop.
  2. At the end of the body, it goes back up to the while line and checks the condition again.
  3. As soon as the condition is false, it skips the body and goes on with the first line after the loop.

One pass through the body is an iteration of the loop, as in the last module. These lessons also call it a round, which is shorter. Here the body runs three times, with number at 1, 2 and 3. After the third round number is 4, the condition 4 <= 3 is false, and the loop ends.

Compare the two conditions. The if before break says when to stop: number > 3. The while condition says when to keep going: number <= 3. One is the opposite of the other. The version with the condition is shorter, and a reader sees right at the top how long the loop runs.

The condition comes first

Python checks the loop condition before every round, the first one included. If the condition is false from the start, the body doesn't run at all:

lap = int(input("Starting lap: "))
while lap <= 5:
    print(f"Lap {lap}")
    lap += 1
print("Race over")
Input
3
Output
Starting lap: 3
Lap 3
Lap 4
Lap 5
Race over

With 8 as the input, 8 <= 5 is false straight away, so after the prompt the program prints only Race over.

The condition is checked only there, at the top. If it becomes false in the middle of the body, the rest of the body still runs, and the loop ends when Python comes back up to check.

Your task

Challenge 1 of 3

Fill in the condition so the program prints the multiples of 5 from 5 to 50, each on its own line.

Challenge 2

What does this program print? Type each line it prints.

Challenge 3

Write a program that asks How many steps? and then prints one line per step, from Step 1 up to the number typed in. After the steps it prints At the top!. Use a while loop with a condition, not while True.

How many steps? 3
Step 1
Step 2
Step 3
At the top!