While loops
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
count = 3
while count > 0:
print(count)
count -= 1
print("Lift off!")3
2
1
Lift off!- Check the condition. If it’s false, skip the loop entirely and carry on after it.
- If it’s true, run the indented block.
- 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:
count = 3
while count > 0:
print(count) # forgot count -= 1This 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.
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:
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:
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.
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.
secret = 42
guesses = 0
# Loop until the guess is correctsecret = 42
guesses = 0
while True:
text = input("Guess: ").strip()
if not text.isdigit():
print("Please type a number")
continue
guess = int(text)
guesses += 1
if guess < secret:
print("Too low")
elif guess > secret:
print("Too high")
else:
print(f"Correct! You took {guesses} guesses.")
breakSummary
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:withbreakis 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.