Lesson 6 of 26 · about 13 min
Repeating with while
A while loop repeats a block of code as long as a condition stays True. Something inside the loop must eventually make it False.
🧭 What you need first: Making decisions
Stirring a sauce: while the sauce is still runny, keep stirring. You don’t decide in advance how many stirs; you check after every stir. The moment it’s thick, you stop.
That’s a while loop. It’s for when you don’t know how many times you’ll need to repeat something, only when to stop.
But beware the cursed recipe: “while the sauce is runny, stir,” with the stove turned off. The sauce never thickens and you stir forever. That’s an infinite loop, the most famous bug in programming.
Another way: a washing machine
A washing machine rinses, then checks the water: still soapy? Rinse again. Clear? Move on. It repeats a step based on a check, not a fixed count.
Another way: “Are we there yet?”
On a road trip, a kid asks “are we there yet?” and keeps asking until the answer is yes. Every question is one round of the loop; arriving is the condition becoming False.
Watch a loop go round
Step through a countdown. Notice the program jumps back up to the while line after each round to check again.
Watch the code run, one step at a time
- 1count = 3
- 2while count > 0:
- 3 print(count)
- 4 count = count - 1
- 5print("Liftoff!")
➜ yellow = the line about to run · ✓ = the line that just ran
Try editing: what happens if you delete count = count - 1? (Our runner will stop it after a few seconds. Real programs aren’t so lucky.)
The real words
while condition:
# the loop body: runs again and again
# while condition is True
# runs once the condition is False- Each trip through the body is called an iteration.
- The condition is checked before every iteration. If it’s False the very first time, the body never runs at all.
- A infinite loop happens when nothing in the body ever makes the condition False. Fix it by making sure each round makes progress toward stopping.
breakjumps out of the loop immediately.while True:with abreakinside is a common way to write “keep going until something happens.”
Three classic patterns:
- Counter: start at 0, add 1 each round, stop at a limit.
- Goal-seeking: repeat until a value reaches a target (savings reach $1,000).
- Sentinel: keep reading input until a special sentinel value like
"quit"or0appears.
Double your savings
You have 100 in savings, and it grows 10% each year. Use a while loop to count how many years until it reaches at least 200. Store the answer in years.
Add numbers until zero
Keep reading numbers and adding them to total until the user types 0 (the sentinel). Then print the total. Keep the typed numbers as they are for the check.
n = 10. How many times does the body run? while n < 5: print(n)
Got it?
Finish the lesson to color it in on your map and collect its concept cards.
Did this lesson click?