While loops

Topic 1 of 4 in Loops6 min readBeginnerFree course

Overview

Computers are great at repetition. A loop runs a block of code again and again. Python has two kinds: for loops go through a collection of items (next lesson), and while loops repeat as long as a condition is true — perfect when you don’t know in advance how many repetitions you’ll need.

How while works

Python
count = 3
while count > 0:
    print(count)
    count -= 1
print("Lift off!")
Text
3
2
1
Lift off!

How a while loop runs. count = 3 is set; then the condition count > 0 is checked. If True, the body runs — print(count) and count -= 1 — and then the condition is checked again. Pass 1 prints 3, pass 2 prints 2, pass 3 prints 1; when count is 0 the condition is False and the program continues with the code after the loop. Forget count -= 1 and the condition never becomes False — an infinite loop. Press Ctrl+C to stop it.

  1. Check the condition. If it’s false, skip the loop entirely and carry on after it.
  2. If it’s true, run the indented block.
  3. Go back to step 1.

The condition is checked before each pass, so if it’s false to begin with, the block never runs.

Infinite loops

If nothing in the loop ever makes the condition false, it runs forever:

Python
count = 3
while count > 0:
    print(count)     # forgot count -= 1

This prints 3 endlessly. Press Ctrl+C in the terminal to stop it (you’ll see KeyboardInterrupt). Before writing a while loop, ask: what changes on each pass, and how does that eventually end the loop?

Looping until the input is valid

A very common use: keep asking until the user gives a usable answer.

Python
age_text = input("Age: ")
while not age_text.isdigit():
    print("Please enter a whole number.")
    age_text = input("Age: ")
age = int(age_text)

str.isdigit() is True when a string is non-empty and contains only digits — a quick check before int(). (It doesn’t accept -5 or 3.5; Errors and exceptions shows the more general approach.)

while True and break

Repeating the input() line before and inside the loop is clumsy. The usual Python idiom is an “infinite” loop with an exit inside:

Python
while True:
    age_text = input("Age: ")
    if age_text.isdigit():
        break                      # leave the loop immediately
    print("Please enter a whole number.")
age = int(age_text)

break ends the loop at once and continues after it. continue skips the rest of the current pass and goes back to the condition. Both get a full lesson in Break and continue.

Sentinel values: stop on a special input

Keep reading until the user types a special “stop” value:

Python
total = 0
while True:
    text = input("Price (or 'done'): ").strip()
    if text == "done":
        break
    total += float(text)
print(f"Total: {total}")

The "done" value that ends the loop is called a sentinel.

Counters and accumulators

Two kinds of variable appear in most loops:

  • a counter counts how many times something happened: guesses += 1;
  • an accumulator builds up a result: total += price, text += line.

Initialise them before the loop (guesses = 0). Initialising inside the loop resets them every pass — a frequent bug.

while vs for

Use while when… Use for when…
you repeat until something happens you go through every item in a collection
the number of repetitions isn’t known you repeat a known number of times
e.g. games, menus, retries, validation e.g. processing a list, counting 1 to 10

If you find yourself writing i = 0; while i < len(items): … i += 1, a for loop is simpler and safer.

Before every while loop, check three things: the variables in the condition start with sensible values, the condition is checked each pass, and something inside the loop moves towards ending it.

Exercise

Guess the number

Write a number-guessing game. The secret number is 42 (later you can use random.randint(1, 100)). Keep asking Guess: until the user gets it right, saying Too low or Too high after each wrong guess. If the user types something that isn’t a whole number, print Please type a number and ask again (use .isdigit()). When they win, print Correct! You took N guesses., counting only valid guesses.

Python
secret = 42
guesses = 0

# Loop until the guess is correct

Summary

  • while condition: repeats its block as long as the condition is true, checking before each pass.
  • Something inside the loop must eventually make the condition false — otherwise it loops forever (Ctrl+C stops it).
  • while True: with break is a clean way to loop until something happens, such as valid input.
  • Use while when you don’t know in advance how many times to repeat; use for when you’re going through items.
  • Counters (count += 1) and accumulators (total += x) are the most common loop variables.