Python While Loops
while repeats a block as long as a condition stays true. Use it when you don't know in advance how many times you'll loop.
Basic
PYTHON
n = 0
while n < 5:
print(n)
n += 1
break, continue, else
| Keyword | What it does |
|---|---|
break | Exit the loop immediately. |
continue | Skip to the next iteration. |
else | Runs when the loop ends naturally (not via break). |
PYTHON
while True:
answer = input('quit? ')
if answer == 'q':
break
print('again')
else:
print('this never runs — we broke out')
The infinite loop pattern
Many event loops, retry handlers, and game loops use this:
PYTHON
while True:
msg = queue.get()
if msg is SENTINEL:
break
handle(msg)
Tip: If you find yourself writing
while index < len(items):, you almost certainly want a for loop with enumerate — shorter and less off-by-one prone.Example
Exercise
Exit a loop immediately.
if done:
Five letters; opposite of continue.
Discussion
Loading…