iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

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

KeywordWhat it does
breakExit the loop immediately.
continueSkip to the next iteration.
elseRuns 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

Example
n = 0
while n < 5:
    print('n =', n)
    n += 1
print('done')
Try it Yourself »

Exercise

Exit a loop immediately.

if done:

Test yourself

Q1. while-else else runs when…
Q2. A common infinite loop pattern is…
Q3. When you know the count, prefer…

Discussion

Loading…