break β Exit the Loop Immediately
break immediately terminates the innermost loop. Execution continues with the first statement after the loop.
# Find first even number and stop
for num in [1, 3, 7, 8, 9, 10]:
if num % 2 == 0:
print(f"Found first even: {num}")
break
print(f"{num} is odd")
print("Loop ended")
continue β Skip to Next Iteration
continue skips the rest of the current iteration and jumps to the next one. The loop itself continues running.
# Print only odd numbers
for num in range(1, 11):
if num % 2 == 0:
continue # Skip even numbers
print(num)
pass β The No-Op Placeholder
pass does nothing. It's used when Python requires a statement syntactically but you don't want to execute anything β useful for stubs, empty classes, and empty except blocks.
# Stub function during development
def calculate_tax(income):
pass # TODO: implement later
# Empty class
class Employee:
pass
# Suppress specific exceptions
try:
result = 10 / 0
except ZeroDivisionError:
pass # We know this can happen, intentionally ignore
break and continue in Nested Loops
Important: break and continue only affect the innermost loop they are in. To break out of multiple nested loops, use a flag variable or structure your code differently.
# break only exits the inner loop
for i in range(3):
for j in range(3):
if j == 1:
break # Exits inner loop only
print(f"({i},{j})")
# Flag to break outer loop too
found = False
for i in range(5):
for j in range(5):
if i * j > 6:
found = True
break
if found:
break
print(f"Stopped at i={i}, j={j}")