while Loops
Repeating while a condition stays True.
4 minute read
Big idea
A while loop repeats its block as long as a condition stays True. Use it when you don't know in advance how many rounds you'll need.
The idea
while condition:
# repeat this
Each round, Python checks the condition. True: run the block, then check again. False: skip past the loop and carry on.
count = 1
while count <= 5:
print(count)
count += 1
print("Done!")output
1
2
3
4
5
Done!Run and edit it in the app.
Watch it
Something must change
If nothing inside the loop ever makes the condition False, it runs forever — an infinite loop. In a terminal you'd stop it with Ctrl+C; here, the run times out.
n = 3
while n > 0:
print(n)
print("Liftoff!")output
3
2
1
Liftoff!Run and edit it in the app.
n never changes, so n > 0 stays True forever. Add n -= 1 inside the loop.
Unknown number of rounds
A classic while job: keep halving until something small is left. You couldn't easily say how many rounds that takes:
n = 100
steps = 0
while n > 1:
n = n // 2
steps += 1
print(steps)What does it print? Show the answer
6Run and edit it in the app.
100 → 50 → 25 → 12 → 6 → 3 → 1: six steps.
Reading until a stop word
while is also the natural shape for "keep reading until the user says stop":
total = 0
number = int(input())
while number != 0:
total += number
number = int(input())
print("Total:", total)input
5
10
20
0output
Total: 35Run and edit it in the app.
How many times does the body run? i = 0 then while i < 3: i += 1
Think of it like
"Keep stirring while the sauce is lumpy." You don't know how many stirs it'll take — you just check after each one.
Key terms
- while loop — Repeats while its condition is True.
- Iteration — One round of a loop.
- Infinite loop — A loop whose condition never becomes False.
Check yourself
When does a while loop stop?
What causes an infinite loop?
When is while a better fit than for?