Level 1 · First Words

Loops That Repeat: while 🔁

Computers are unbelievably good at doing the same thing over and over without complaining. This is the lesson where you stop copying and pasting.

while: keep going until

grog = 5

while grog > 0:
    print(f"{grog} mugs of grog on the wall")
    grog -= 1

print("The bar is dry.")
5 mugs of grog on the wall
4 mugs of grog on the wall
3 mugs of grog on the wall
2 mugs of grog on the wall
1 mugs of grog on the wall
The bar is dry.

The shape is always the same, and it has exactly three moving parts:

  1. Set something up before the loop (grog = 5).
  2. Ask a question at the top. True means go round again, false means stop.
  3. Change something inside the loop so the answer eventually becomes false (grog -= 1).

Miss step three and the loop runs forever. Which is next.

The infinite loop, and the escape hatch

grog = 5

while grog > 0:
    print("still 5 mugs, forever, until the heat death of the universe")
    # grog never changes, so the condition is never false
REACTION SPEED[Easy: Success]

Ctrl+C. In the terminal, hold Control and press C. The program stops immediately. Not Cmd+C on a Mac, Control+C, on every platform. Learn it now, use it today.

In this school's playground, the run button gives up after twenty seconds and tells you so, which is friendlier than freezing your browser. On your own machine, Ctrl+C is the answer. Writing an infinite loop is a rite of passage, not a disaster, and everybody has done it.

Waiting for the right answer

answer = ""

while answer != "swordfish":
    answer = input("Password: ")
    if answer != "swordfish":
        print("  That is not the password.")

print("The door swings open.")
Password: grog
  That is not the password.
Password: monkey
  That is not the password.
Password: swordfish
The door swings open.

This is the classic use of while: you do not know in advance how many times it will run. That is the whole difference between while and the for loop in the next lesson. Unknown number of repeats: while. Known collection to walk through: for.

break: leave immediately

while True:
    command = input("> ")
    if command == "quit":
        print("Farewell.")
        break
    print(f"You try to {command}. Nothing happens.")
> look
You try to look. Nothing happens.
> take grog
You try to take grog. Nothing happens.
> quit
Farewell.

while True: with a break inside is a completely respectable pattern, not a cheat. It says "loop until I decide to stop", and it is the standard shape for menus, game loops and command prompts. The important thing is that a break exists somewhere and is reachable.

continue: skip the rest of this round

number = 0

while number < 10:
    number += 1
    if number % 2 == 0:
        continue          # jump straight back to the top
    print(f"{number} is odd")
1 is odd
3 is odd
5 is odd
7 is odd
9 is odd
🪤 continue in a while loop is a trap

If your continue jumps back before the line that changes the counter, you get an infinite loop. In the example above, number += 1 is the very first line for exactly that reason. Move it to the bottom and the program hangs at 2, forever.

while / else, a Python curiosity

attempts = 3

while attempts > 0:
    print(f"{attempts} attempts left")
    attempts -= 1
else:
    print("Ran out of attempts, and no break happened.")
3 attempts left
2 attempts left
1 attempts left
Ran out of attempts, and no break happened.

The else on a loop runs only if the loop finished naturally, without a break. It is genuinely useful for searches ("if we got through the whole list without finding it..."), rare in the wild, and confusing enough that many style guides discourage it. Know it exists so it does not startle you in someone else's code.

A real one: the number guessing game

import random

secret = random.randint(1, 100)
guesses = 0

while True:
    guess = int(input("Guess (1-100): "))
    guesses += 1

    if guess < secret:
        print("  Higher.")
    elif guess > secret:
        print("  Lower.")
    else:
        print(f"Got it in {guesses} guesses.")
        break

That is a complete, genuinely fun program in fourteen lines, and it is Project 1 in the workshop, where you build it properly with input validation and a play-again loop.

Exercise 1

Countdown

Count down from 10 to 1, then print 'Liftoff'. One line per number.

Reveal solution
n = 10

while n > 0:
    print(n)
    n -= 1

print("Liftoff! 🚀")
10
9
8
7
6
5
4
3
2
1
Liftoff! 🚀
Exercise 2

Sum until zero

Keep asking for numbers and adding them up. When the user enters 0, stop and print the total and how many numbers were given.

Reveal solution
total = 0
count = 0

while True:
    number = int(input("Number (0 to finish): "))
    if number == 0:
        break
    total += number
    count += 1

print(f"{count} numbers, total {total}")
Number (0 to finish): 5
Number (0 to finish): 10
Number (0 to finish): 3
Number (0 to finish): 0
3 numbers, total 18

A value that means 'stop' is called a sentinel. It is a standard technique, and its weakness is that the sentinel can never be real data: this program can never total a genuine zero.

Exercise 3

Why does this never end?

Spot the bug without running it. There are two ways to fix it.

count = 1
while count < 5:
    print(count)
count += 1
Reveal solution

count += 1 is outside the loop: it is not indented. So count is 1 forever, the condition is true forever, and the loop prints 1 until the sun burns out.

count = 1
while count < 5:
    print(count)
    count += 1
1
2
3
4

The other fix is a for loop, which removes the possibility entirely by counting for you. That is the next lesson, and it is why experienced Python programmers reach for for far more often than while.

+100 XP