Loop Control (break, continue)
Overview
Sometimes you need to interrupt the normal sequential flow of a loop based on an event. The break statement immediately terminates the loop entirely, exiting the block. The continue statement acts as a skip button; it aborts the current iteration and instantly jumps back to the top of the loop for the next cycle. These are essential for writing clean search algorithms and filtering data.
Syntax
print("--- Demonstrating Continue ---")
for i in range(5):
if i == 2:
continue # Skips everything below for i=2
print(i)
# Outputs: 0, 1, 3, 4 (Notice 2 is missing)
print("--- Demonstrating Break ---")
for i in range(5):
if i == 3:
break # Destroys the loop entirely
print(i)
# Outputs: 0, 1, 2Common Pitfalls
- Placing logic you wanted executed after a
continuestatement. Anything belowcontinueinside the loop block is ignored. - Expecting
breakto exit all nested loops. If you have a loop inside a loop,breakonly terminates the innermost loop it resides within.
Interview Questions
pass statement, and how does it differ from continue?pass is a null operation; it literally does nothing. It is used purely as a syntactic placeholder when Python requires an indented block but you don't want to execute any code. continue actively affects flow control by jumping to the next iteration.
Real-World Example
Searching a large list and optimizing performance by breaking early once the target is found.
files_to_scan = ["log.txt", "data.csv", "malware.exe", "image.png"]
for file in files_to_scan:
if file.endswith(".exe"):
print(f"DANGER: Executable found ({file}). Halting scan!")
break # No need to waste CPU checking remaining files
print(f"Scanned {file} safely.")Check Your Knowledge
Test your understanding of Loop Control (break, continue) with these quick questions.