Loop Control: break, continue, & else
Sometimes, the standard “top-to-bottom” execution of a loop isn’t enough. You might need to stop early because you found what you were looking for, or skip a specific record that contains invalid data.
Python provides four tools for fine-tuning loop behavior: break, continue, pass, and the powerful (but often misunderstood) else clause.
1. break: The Emergency Exit
Section titled “1. break: The Emergency Exit”The break statement immediately terminates the innermost loop and jumps to the first line of code after the loop block.
# Find the first multiple of 7 in a listdata = [12, 18, 21, 28, 30]
for num in data: if num % 7 == 0: print(f"Found it: {num}") break # Stop the loop entirelyUnder the Hood
Section titled “Under the Hood”When Python hits break, it discards the loop’s iterator and moves the “Instruction Pointer” to the end of the loop’s bytecode. This is an extremely efficient way to stop processing.
2. continue: The Skip Button
Section titled “2. continue: The Skip Button”The continue statement stops the rest of the current iteration and jumps back to the top of the loop for the next cycle.
emails = ["alice@gmail.com", "", "bob@yahoo.com", "invalid-email"]
for email in emails: if not email or "@" not in email: continue # Skip to the next email send_notification(email)Note: In a for loop, continue fetches the next item. In a while loop, it re-evaluates the condition.
3. pass: The Placeholder
Section titled “3. pass: The Placeholder”pass is a null operation. It literally does nothing. Because Python uses indentation to define blocks, you cannot have an “empty” block.
def process_data(data): for item in data: if item.is_valid(): # TODO: Implement processing logic pass else: log_error(item)Context: Use pass as a temporary placeholder while sketching out your program’s structure.
4. The Loop else Clause (Deep Dive)
Section titled “4. The Loop else Clause (Deep Dive)”This is one of Python’s most “hidden” features. An else block attached to a loop behaves differently than an else attached to an if.
Rule: The else block executes ONLY if the loop completed naturally (i.e., it was NOT terminated by a break).
The “Search and Handle” Pattern
Section titled “The “Search and Handle” Pattern”This is the most common professional use for the loop-else. It allows you to handle the “Not Found” case without using a “flag” variable.
found = Falsefor x in data: if x == target: found = True breakif not found: print("Not found")for x in data: if x == target: print("Found!") breakelse: # This only runs if the loop finishes # without finding the target! print("Not found")5. Summary Table
Section titled “5. Summary Table”| Statement | Effect on Loop | Next Action |
|---|---|---|
break | Terminates loop. | Jumps to code after the loop. |
continue | Skips current iteration. | Jumps back to start of loop. |
pass | No effect. | Continues with next line in block. |
else | Logic for completion. | Runs if no break occurred. |