while Loops
Repeat as long as something stays true
In this lesson
A while loop repeats as long as a condition is true. Use it when you don’t know in advance how many times you’ll loop — you just keep going until something changes.
Explain it like I’m 5
‘Keep doing this while the answer is yes.’ Python checks the question before every round and stops the moment the answer becomes no.
Condition first, then body
A while loop checks its condition before each pass. If the condition is true, the indented body runs, then Python rechecks the condition and repeats. As soon as the condition is false, the loop ends and execution continues below it. If the condition is false on the very first check, the body never runs at all.
balance = 100
withdrawal = 30
while balance >= withdrawal:
balance = balance - withdrawal
print("Withdrew 30, balance now", balance)
print("Not enough for another withdrawal. Left:", balance)
Withdrew 30, balance now 70 Withdrew 30, balance now 40 Withdrew 30, balance now 10 Not enough for another withdrawal. Left: 10
Something must change inside the loop
The critical rule: something inside the loop must eventually make the condition false, or the loop runs forever — an infinite loop. Usually that means updating a counter or a flag each pass. Always ask: ‘what makes this loop stop?’ before you run it.
This loop should print 5, 4, 3, 2, 1 then 'Liftoff!' — but it's missing the line that changes n. Add it so the loop ends.
n = 5
while n > 0:
print(n)
print("Liftoff!")
Inside the loop, subtract 1 from n each pass so the condition eventually becomes false.
n = 5
while n > 0:
print(n)
n = n - 1
print("Liftoff!")
5
4
3
2
1
Liftoff!
break and continue with while
break exits immediately, even if the condition is still true — handy for ‘loop forever until I find/receive X’. continue jumps back to the condition check, skipping the rest of the current pass. A common pattern is while True: with a break inside when you’re done.
total = 0
while True:
total += 10
print("total is now", total)
if total >= 30:
break
print("Reached the goal.")
total is now 10 total is now 20 total is now 30 Reached the goal.
The 'loop until valid' pattern
while shines for retrying until input is acceptable: keep prompting until the user types a valid value. Because you can’t know how many wrong tries they’ll make, a count-based for loop won’t fit — the condition (‘not valid yet’) is what drives it.
# Stand-ins for what a user might type, in order:
typed = ["", " ", "Ada"]
i = 0
name = typed[i].strip()
while not name:
i += 1
name = typed[i].strip()
print("Welcome,", name)
Welcome, Ada
Flags and sentinel values
Two patterns make while loops read clearly when a simple counter won’t do. A flag is a boolean that records ‘keep going’ or ‘stop’: running = True … while running:, and you set it to False when you’re done. A sentinel is a special value that means ‘stop’ — like looping over input until the user types quit.
Both give the loop a readable, intention-revealing stop condition instead of a magic number.
# Stand-in for what a user might type, in order:
commands = ["add", "add", "quit", "add"]
i = 0
running = True
while running:
command = commands[i]
if command == "quit":
running = False
else:
print("Running:", command)
i += 1
print("Stopped.")
Running: add Running: add Stopped.
Common mistake: Forgetting to update the loop variable (infinite loop)
If the condition never becomes false because nothing inside the loop changes it, the loop runs forever.
Make sure each pass moves you toward the stop condition — decrement a counter, set a flag, or break on a clear event.
n = 5
while n > 0:
print(n)
n -= 1 # this line is what ends the loop
When does a while loop stop?
The condition is tested before every iteration; the loop ends the first time it’s false.
What causes an infinite loop?
If the condition can never become false, the loop never ends.
Mini exercise (medium)
Start with total = 0 and a counter n = 1. Using a while loop, add n to total, then increase n by 1, until total first exceeds 50. Print how many numbers it took.
Do it here. Finish the code below and press Run to try your answer right in the browser — no setup needed.
total = 0
n = 1
count = 0
# TODO: while total <= 50, add n to total, then grow n by 1 and add 1 to count each time n grows.
print(count)
Loop while total <= 50:, doing total += n then n += 1 and count += 1 each pass.
total = 0
n = 1
count = 0
while total <= 50:
total += n
n += 1
count += 1
print(count)
10
__no_output_bypass__ = True
import ast as _ast
assert any(isinstance(n, _ast.While) for n in _ast.walk(_ast.parse(__user_code__))), "use a while loop — not a for loop or hardcoded values"
__no_output_bypass__ = False
assert total > 50 and count == 10, "it takes 10 numbers to push the total past 50"
print("✓ Took", count, "numbers!")