Python · Module 2 · Lesson 31 min read

while Loops, break & continue

while loops

A while loop repeats as long as its condition is True. Use it when you don't know in advance how many times to loop (menus, retries, games).

break and continue

  • break → exit the loop immediately
  • continue → skip the rest of this round and go to the next one

The "loop until valid" pattern

Python
while True:
    answer = input("yes/no? ")
    if answer in ("yes", "no"):
        break

Infinite loops ⚠️

If the condition never becomes False the loop runs forever. Always make sure something inside changes the condition (count += 1). In this app, programs are stopped after 15 seconds.

💡 Prefer for when you're counting or walking through a collection, and while when you're waiting for something to happen.

▶️ Runs in the app.

Example

Python
count = 0
while count < 5:
    count += 1
    if count == 3:
        continue          # skip 3
    print(count, end=" ")
print()                   # 1 2 4 5

# Find the first number divisible by 7 and 5
n = 1
while True:
    if n % 7 == 0 and n % 5 == 0:
        break
    n += 1
print("Found:", n)        # Found: 35

# Countdown
seconds = 3
while seconds > 0:
    print(seconds)
    seconds -= 1
print("Go!")