Python Arena
Step 2 of 4

Start, condition, update

A loop that counts needs three things. Here they are in a loop that prints the times of a bus that leaves every two hours:

hour = 9  # 1. the start value
while hour <= 17:  # 2. the condition
    print(f"{hour}:00")
    hour += 2  # 3. the update
Output
9:00
11:00
13:00
15:00
17:00
  1. Initialization: before the loop, the variable in the condition gets its first value. Here hour starts at 9.
  2. Condition: at the top of the loop, it decides whether another round runs.
  3. Update: in the body, the variable changes, so that every round brings the loop closer to its end. Here hour grows by 2 in every round, so sooner or later hour <= 17 is false.

If one of the three is missing or wrong, the loop goes wrong too.

Forgetting the start value

Without an initialization, the variable doesn't exist yet when Python first checks the condition:

while total < 100:
    total += 30
print(total)
Python stops with
Traceback (most recent call last):
  File "main.py", line 1, in <module>
    while total < 100:
          ^^^^^
NameError: name 'total' is not defined

The fix is a line before the loop that gives total its start value, such as total = 0.

Forgetting the update

Without an update, the condition never changes. If it's true once, it stays true forever:

hour = 9
while hour <= 17:
    print(f"{hour}:00")

This prints 9:00 again and again, without end: an infinite loop, like the ones in the last module. On your own computer you stop such a program with Ctrl+C. On this site, a program that runs for more than a few seconds, or prints a huge amount, is stopped for you, with a note that says so.

A sneakier way to lose the update is to forget its indentation:

hour = 9
while hour <= 17:
    print(f"{hour}:00")
hour += 2

hour += 2 isn't indented, so it isn't part of the body. Only the indented lines repeat; this line would run once the loop is over, and the loop is never over.

The update can also go the wrong way. With hour -= 2, hour gets smaller in every round and stays below 17 forever. So before you run a loop, ask yourself: does every round take a step toward making the condition false?

Your task

Challenge 1 of 3

This program should print Round 1 to Round 4 and then Game over, but it never stops. Fix it.

Round 1
Round 2
Round 3
Round 4
Game over

Challenge 2

Fill in the start value, the condition and the update, so the program prints the battery levels below and then Empty.

100
75
50
25
Empty

Challenge 3

Write a program that asks for two whole numbers with the prompts From: and To: , and prints every whole number from the first one to the second one, in order. If the first number is greater than the second, it prints no numbers at all.

From: 4
To: 7
4
5
6
7