Beginner-Friendly Topic
Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on. You've got this! 🚀
break, continue & pass
break exits a loop immediately, continue skips to the next iteration, and pass is a placeholder that does nothing. These control flow tools give you fine-grained control over loop execution.
Loop Control
# break - exit the loop immediately
for i in range(10):
if i == 5:
print("Found 5, stopping!")
break
print(i, end=" ") # 0 1 2 3 4
print()
# continue - skip current iteration
print("Odd numbers:")
for i in range(10):
if i % 2 == 0:
continue # skip even numbers
print(i, end=" ") # 1 3 5 7 9
print()
# pass - placeholder (does nothing)
for i in range(5):
if i == 3:
pass # TODO: handle this case later
print(i, end=" ") # 0 1 2 3 4
print()
# Practical: find first negative number
numbers = [4, 7, -2, 9, -5, 3]
for num in numbers:
if num < 0:
print(f"First negative: {num}")
break
# for-else: runs if loop completes without break
for num in [2, 4, 6, 8]:
if num % 2 != 0:
print("Found odd!")
break
else:
print("All numbers are even!")Tip
Tip
The for/else pattern is unique to Python. The else block runs only if the loop completes without break. Perfect for search loops.
for loops for known counts, while loops until a condition is met
Common Mistake
Warning
Confusing break and continue. break exits the entire loop; continue skips only the current iteration. Test both in a simple loop.
Practice Task
Note
(1) Find the first negative number in a list using break. (2) Skip even numbers using continue. (3) Use for/else to check if a list contains a prime.