🕯️ Magic Note
Unlike many other languages, Python does not have a goto statement or a labeled break. The designers of Python intentionally kept loop control simple. break exits only the innermost loop. If you need to exit multiple nested loops, you need a flag variable or to wrap the loops in a function and use return.
Python
# break in a for loop
for num in range(1, 101):
if num ** 2 > 50:
break
print(f”{num}^2 = {num**2}”)
# Output:
# 1^2 = 1
# 2^2 = 4
# 3^2 = 9
# 4^2 = 16
# 5^2 = 25
# 6^2 = 36
# 7^2 = 49
# (Stops at 8^2 = 64, no output)
Python
# Searching a list with break
fruits = [“apple”, “banana”, “cherry”, “date”, “elderberry”]
target = “cherry”
i = 0
found = False
while i < len(fruits):
if fruits[i] == target:
found = True
break
i += 1
if found:
print(f”Found {target} at index {i}”)
else:
print(f”{target} not found”)
🕯️ Magic Note
The combination of while True and break is a common pattern for loops that should run until a condition in the middle becomes true. This is sometimes called “loop and a half” because the exit condition is not at the top or bottom but inside.
Python
# Loop and a half pattern
while True:
name = input(“Enter your name (or ‘quit’ to exit): “)
if name == “quit”:
break
print(f”Hello, {name}!”)
# This loop checks the exit condition in the middle
Python
# Print only odd numbers using continue
for num in range(1, 11):
if num % 2 == 0:
continue
print(num, end=” “)
# Output: 1 3 5 7 9
# Skip empty strings
words = [“hello”, “”, “world”, “”, “python”, “magic”]
for word in words:
if word == “”:
continue
print(f”Processing: {word}”)
Python
# Danger: infinite loop with continue
x = 0
while x < 10:
if x % 2 == 0:
continue # x never changes when x is even!
print(x)
x += 1
# This loop will never reach x += 1 when x is 0
# Correct way: update before continue or use for loop
for x in range(10):
if x % 2 == 0:
continue
print(x)
| break | continue |
|---|---|
| Exits the entire loop immediately | Skips only the current iteration |
| Loop stops completely | Loop continues with next item |
| Used when you found what you need | Used when you want to skip certain items |
| Example: searching, game over | Example: filtering, skipping invalid data |
Python
# Visual comparison
for i in range(1, 6):
if i == 3:
break
print(i, end=” “)
# Output: 1 2 (loop stops at 3)
for i in range(1, 6):
if i == 3:
continue
print(i, end=” “)
# Output: 1 2 4 5 (3 is skipped)
Python
# Empty loop (placeholder)
for i in range(10):
pass # TODO: implement later
# Empty function
def not_ready_yet():
pass
# Empty class
class MyClass:
pass
# In a conditional (placeholder)
error_code = 200
if error_code == 200:
pass # Success – do nothing
else:
print(f”Error: {error_code}”)
🕯️ Magic Note
pass is unique to Python (and a few other languages). It is useful for stub functions, empty classes, and loops that will be filled later. Unlike a comment, pass is actual executable code. It just does nothing.
Python
# break only affects the inner loop
for i in range(3):
print(f”Outer loop: {i}”)
for j in range(5):
if j == 2:
break
print(f” Inner: {j}”)
print(“Inner loop ended, outer continues”)
# Output shows outer loop runs 3 times
# Each inner loop only prints j=0,1 then breaks
Python
# Breaking out of nested loops with a flag
found = False
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
target = 5
for row in matrix:
for col in row:
if col == target:
found = True
break
if found:
break
print(f”Found {target}!” if found else “Not found”)
Python
# Elegant search with for-else
numbers = [1, 3, 5, 7, 9]
target = 4
for num in numbers:
if num == target:
print(f”Found {target}”)
break
else:
print(f”{target} not found”)
# This pattern works with while as well
Python
# Keep asking until valid input
while True:
try:
age = int(input(“Enter your age: “))
if 0 <= age <= 120:
break
print(“Age must be between 0 and 120”)
except ValueError:
print(“Please enter a valid number”)
print(f”Age: {age}”)
- Using break when you meant continue (exits instead of skipping)
- Using continue in a while loop and skipping the increment (infinite loop)
- Expecting break to exit all nested loops (it only exits the innermost)
- Using pass when you actually need a comment
- Leaving pass in production code accidentally
- Forgetting that else runs when no break occurs
- What is the difference between break and continue?
- Write a loop that prints numbers from 1 to 10 but stops at 7 using break.
- Write a loop that prints only even numbers from 1 to 10 using continue.
- What does pass do? Give an example of when to use it.
- How do you break out of multiple nested loops?
- What triggers the else clause in a loop?
⚡ Whisper
Three small words. break. continue. pass. Each one a tiny spell. break is the escape door. It lets you leave the loop when you have found what you seek. No extra steps. No wasted time. continue is the skip stone. It lets you jump over what you do not need and move to the next. pass is the silence. It does nothing, but it holds the space for something you will write tomorrow. Use these spells well. break too soon and you miss what comes after. continue too much and your logic becomes a maze. pass forever and nothing ever happens. Balance is the key. Know when to stop. Know when to skip. Know when to wait. These are not just loop controls. They are lessons in patience and precision.