Loading...
Loading...
Control loop flow with break and continue
Sometimes you need to exit a loop early (break) or skip the current iteration (continue). These are loop control statements that give you finer control over when and how the loop runs.
# Break — exit the loop immediately
for n in [1, 2, 3, 4, 5]:
if n == 3:
break # Loop stops here
print(n)
# Output: 1, 2
# Continue — skip to the next iteration
for n in [1, 2, 3, 4, 5]:
if n == 3:
continue # Skip 3, move to 4
print(n)
# Output: 1, 2, 4, 5for i in range(1, 11):
if i == 5:
print("Found 5, stopping!")
break
print(f"Checking {i}...")
print("Loop ended")Output:
Checking 1...
Checking 2...
Checking 3...
Checking 4...
Found 5, stopping!
Loop endedbreak immediately jumps out of the loop, skipping all remaining iterations. The program continues with the code after the loop.
for n in range(1, 11):
if n % 2 == 0:
continue # Skip even numbers
print(f"{n} is odd")Output:
1 is odd
3 is odd
5 is odd
7 is odd
9 is oddcontinue skips the rest of the current iteration and jumps to the next one. The loop doesn't stop — it just skips one round.
guests = ["Alice", "Bob", "Charlie", "Diana"]
search = "Charlie"
found = False
for guest in guests:
if guest == search:
found = True
print(f"{search} is on the list!")
break # No need to check further
if not found:
print(f"{search} is NOT on the list.")| ❌ Wrong | Why | ✅ Right |
|---|---|---|
| Using `break` when you meant `continue` | `break` exits the entire loop | Use `continue` to skip one iteration |
| `break` outside a loop | Syntax error — `break`/`continue` only work inside loops | Check your indentation |
| Forgetting to handle the "not found" case | Search loops that never find anything | Use a flag variable to track success |
Write a program that:
nums = [4, 7, 9, 12, 15, 18, 21]
for n in nums:
if n < 10:
continue
if n > 20:
break
print(n)