Topic 43 of 64
break, continue, pass
Overview
break exits the innermost loop immediately, continue skips to the next iteration, and pass is a no-op placeholder. These controls allow precise loop flow management essential in search algorithms and data filtering.
Syntax
python
# break — exit loop immediately
for i in range(10):
if i == 5:
break
print(i) # 0, 1, 2, 3, 4
# continue — skip current iteration
for i in range(10):
if i % 2 == 0:
continue
print(i) # 1, 3, 5, 7, 9
# pass — syntactic placeholder (does nothing)
for i in range(5):
pass # valid empty loopCommon Pitfalls
- break/continue only affect the innermost loop — use a flag variable or extract to a function to break outer loops.
- The for/else and while/else clauses run only if the loop didn't exit via break — useful for search patterns.
- Interview tip: 'pass' is commonly used as a placeholder in empty class bodies, function stubs, or except blocks during development.
Real-World Example
Search through a list and stop at first match
example
python
def find_first_admin(users: list[dict]) -> dict | None:
for user in users:
if not user.get("active"):
continue # skip inactive
if user.get("role") == "admin":
break # found — stop searching
else:
return None # no admin found (no break triggered)
return user
users = [
{"name": "Bob", "role": "user", "active": True},
{"name": "Alice", "role": "admin", "active": True},
]
print(find_first_admin(users)) # Alice's dict