Python While Loops
A while loop repeats a block as long as a condition stays true. Use it when you don't know in advance how many repetitions you need — "keep going until the data runs out", "retry until it succeeds".
Basic while
count = 1
while count <= 5:
print("Count is", count)
count += 1
print("Done")Count is 1
Count is 2
Count is 3
Count is 4
Count is 5
Done
Every while loop needs three things: a variable that's set up before the loop, a condition that tests it, and something inside the loop that changes it. Forget the last part and the condition never becomes false — an infinite loop.
Tip: If you accidentally start an infinite loop in a playground, ExcelTAD stops it after a timeout. In a terminal, press Ctrl+C.
A loop that doesn't know its length
Here is a typical "until" problem: how many years until savings double at 7% interest?
balance = 1000.0
years = 0
while balance < 2000:
balance *= 1.07
years += 1
print(f"{years} years, final balance {balance:.2f}")11 years, final balance 2104.85
break — leave the loop early
break exits the loop immediately, skipping the rest of the body and the remaining iterations:
numbers = [4, 9, 15, 22, 7]
i = 0
while i < len(numbers):
if numbers[i] > 10:
print("First number above 10:", numbers[i])
break
i += 1First number above 10: 15
A common pattern is while True: with a break inside, for loops whose exit condition is easiest to check in the middle:
commands = ["start", "status", "stop", "never reached"]
position = 0
while True:
cmd = commands[position]
position += 1
if cmd == "stop":
print("Stopping.")
break
print("Running command:", cmd)Running command: start
Running command: status
Stopping.
continue — skip to the next iteration
continue jumps straight back to the condition check, skipping the rest of the current pass:
n = 0
while n < 10:
n += 1
if n % 3 != 0:
continue
print(n, "is divisible by 3")3 is divisible by 3
6 is divisible by 3
9 is divisible by 3
Notice that n += 1 comes before continue. If it came after, continue would skip it and the loop would never end.
while … else
A loop may have an else block. It runs when the loop ends normally (the condition became false), but not when it was left with break. This is handy for searches:
def find_divisor(n):
d = 2
while d * d <= n:
if n % d == 0:
print(n, "is divisible by", d)
break
d += 1
else:
print(n, "is prime")
find_divisor(91)
find_divisor(97)91 is divisible by 7
97 is prime
Loop control summary
| Statement | Effect |
|---|---|
break |
Exit the loop now; else is skipped |
continue |
Skip to the next condition check |
else: |
Runs if the loop finished without break |
pass |
Does nothing (placeholder) |
Note: When you are going through the items of a list, string or range, a
forloop (next lesson) is simpler and safer than managing an index withwhile.
Test yourself
When does the else block of a while loop run?
- Always
- Only when the loop body never ran
- When the loop ends without hitting
break - Only after a
continue
What happens if the variable in the condition is never changed inside the loop?
- The loop runs once
- Python raises an error
- The loop may run forever
- The loop is skipped