Skip to content

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.


The break statement immediately terminates the innermost loop and jumps to the first line of code after the loop block.

search_logic.py
# Find the first multiple of 7 in a list
data = [12, 18, 21, 28, 30]
for num in data:
if num % 7 == 0:
print(f"Found it: {num}")
break # Stop the loop entirely

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.


The continue statement stops the rest of the current iteration and jumps back to the top of the loop for the next cycle.

clean_data.py
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.


pass is a null operation. It literally does nothing. Because Python uses indentation to define blocks, you cannot have an “empty” block.

placeholder.py
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.


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).

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 = False
for x in data:
if x == target:
found = True
break
if not found:
print("Not found")

StatementEffect on LoopNext Action
breakTerminates loop.Jumps to code after the loop.
continueSkips current iteration.Jumps back to start of loop.
passNo effect.Continues with next line in block.
elseLogic for completion.Runs if no break occurred.