Break and Continue
Control loop execution with break and continue statements.
The break and continue statements give you fine-grained control over loop execution. Break lets you exit a loop early when a condition is met, while continue skips the rest of the current iteration and moves to the next. These tools are essential for writing efficient loops that handle special cases gracefully.
📚 Concepts & Theory
The break Statement
Exits the loop immediately:
for i in range(10):
if i == 5:
break
print(i)
# Prints: 0, 1, 2, 3, 4
The continue Statement
Skips to the next iteration:
for i in range(5):
if i == 2:
continue
print(i)
# Prints: 0, 1, 3, 4 (skips 2)
Common Use Cases
Search and stop:
for user in users:
if user.name == "Alice":
found = user
break
Skip invalid items:
for item in data:
if not item.is_valid():
continue
process(item)
With while Loops
while True:
response = input("Enter quit to exit: ")
if response == "quit":
break
print(f"You entered: {response}") 🎯 Your Challenge
Write a for loop that iterates through numbers 1 to 10. Use continue to skip even numbers (print only odd numbers). Use break to stop the loop when you reach 7.
📝 Starter Code
# Print odd numbers from 1 to 10, but stop at 7
for i in range(1, 11):
# Skip even numbers
if i % 2 == 0:
# Stop at 7
if i == 7:
print(i)
- continue skips the rest of the loop body
- break exits the loop entirely
- Check for skip conditions before break conditions
- i % 2 == 0 checks if a number is even
Solution
for i in range(1, 11):
if i % 2 == 0:
continue
if i == 7:
break
print(i)
Explanation
For each number, we first check if it is even (i % 2 == 0) and skip it with continue. Then we check if we have reached 7 and exit with break. This prints only 1, 3, 5.
⚠️ Common Mistakes to Avoid
- Putting break before continue (wrong order)
- Using break when you mean continue
- Forgetting that break only exits the innermost loop
- Not understanding that code after continue is skipped