break, continue, and pass in Python: Loop Control That Changes Execution Flow
Standard loop behaviour is sequential: run the body, check the condition, repeat until done. break, continue, and pass let you deviate from that sequence in controlled ways. Each has a precise meaning β they are not interchangeable.
break: Exit the Loop Immediately
break terminates the current loop regardless of the condition. Execution resumes at the first statement after the loop.
words = ["apple", "banana", "cherry", "TARGET", "dragonfruit", "elderberry"]
for word in words: if word == "TARGET": print(f"Found it at index {words.index(word)}") break print(f"Checking: {word}")
# Checking: apple# Checking: banana# Checking: cherry# Found it at index 3# (loop ends here β "dragonfruit" and "elderberry" are never checked)Once break runs, Python exits the for loop and does not process the remaining items.
break in while Loops
break is especially common in while True loops where the exit condition is evaluated in the middle of the loop body:
import random
rolls = 0while True: die = random.randint(1, 6) rolls += 1 print(f"Rolled {die}") if die == 6: print(f"Got a 6 after {rolls} roll(s)!") breakbreak Only Exits One Level
In nested loops, break exits only the innermost loop:
for i in range(3): for j in range(3): if j == 1: break # exits inner loop only print(f"i={i} j={j}") print(f"outer i={i} continues")
# i=0 j=0# outer i=0 continues# i=1 j=0# outer i=1 continues# i=2 j=0# outer i=2 continuesTo break out of multiple levels, use a flag, return, or an exception.
continue: Skip to the Next Iteration
continue stops the current iteration and goes back to the loop condition check (for while) or the next item (for for). The rest of the loop body is skipped for this iteration.
data = [3, -1, 7, -4, 2, -9, 8]
positive_sum = 0for value in data: if value < 0: continue # skip negatives positive_sum += value
print(positive_sum) # 20Using continue for Input Validation
lines = ["Alice,30", "", "Bob,25", " ", "Carol,28", "bad-line"]
records = []for line in lines: line = line.strip() if not line: continue # skip blank lines
parts = line.split(",") if len(parts) != 2: print(f"Skipping malformed line: {line!r}") continue # skip lines that don't have exactly two parts
name, age_str = parts try: records.append({"name": name, "age": int(age_str)}) except ValueError: print(f"Non-integer age in: {line!r}") continue
print(records)# [{'name': 'Alice', 'age': 30}, {'name': 'Bob', 'age': 25}, {'name': 'Carol', 'age': 28}]Using continue to filter bad data early keeps the main processing logic clean and unindented.
continue in while Loops
Be careful: continue in a while loop jumps to the condition check, so your counter or state update must happen before the continue or you risk an infinite loop.
count = 0while count < 10: count += 1 # update BEFORE continue, or the loop never terminates if count % 3 == 0: continue print(count, end=" ")
# 1 2 4 5 7 8 10pass: Do Nothing, Satisfy the Syntax
Python requires a body for every block β if, for, while, class, def. When you want an empty body, pass is the placeholder. It does nothing at all; it simply prevents a SyntaxError.
for i in range(5): pass # loop runs 5 times but does nothing β valid, rarely useful
# More common: empty function or class skeletonclass FutureFeature: pass # implementation coming later
def handle_event(event): if event.type == "resize": pass # TODO: handle window resize elif event.type == "click": process_click(event)pass is not the same as continue. continue actively skips to the next iteration. pass does nothing β execution continues with whatever comes after pass in the block.
for i in range(5): if i == 2: pass # does nothing β continues to print below print(i)
# 0# 1# 2 β printed even though i == 2 (pass did nothing)# 3# 4
for i in range(5): if i == 2: continue # skips to next iteration print(i)
# 0# 1# 3 β 2 is skipped# 4for/else and while/else
Both loop types support an else clause. This clause runs only if the loop completed without hitting a break. This is often described as βran to completionβ vs βexited early.β
# Search example: else handles "not found"def contains_prime(numbers): for n in numbers: if n < 2: continue for divisor in range(2, int(n ** 0.5) + 1): if n % divisor == 0: break else: # Inner else: runs when inner for completed without break # (meaning n is prime) return True return False
print(contains_prime([4, 6, 8, 11])) # Trueprint(contains_prime([4, 6, 8, 10])) # FalseThe for/else pattern is useful for search loops: else fires when the target was not found.
Practical Guidelines
Use break for early exit β searching, error detection, user cancellation. Stop as soon as you have what you need.
Use continue for skipping β filtering data, ignoring errors, bypassing irrelevant iterations. The pattern if bad_condition: continue is cleaner than wrapping the entire body in if good_condition:.
Use pass for stubs and placeholders β empty class bodies, unimplemented branches, code scaffolding.
Avoid overusing break and continue in long loops β two or more break/continue statements in the same loop often indicate the loop is doing too much. Consider extracting the body into a function that returns early.