Loop Control Statements
Alter and fine-tune loop execution using break, continue, pass, and Python's unique loop else clause.
Under normal conditions, a loop repeats with predictable rhythm: it runs iteration 1, then iteration 2, then iteration 3, until its collection is exhausted or its condition becomes False.
However, real-world software constantly faces unexpected scenarios that require immediate course corrections:
- You are searching through a database of 500,000 customers. You find the exact customer you need at record #12. Should the computer waste processing power checking the other 499,988 records? No, you want to stop immediately.
- You are processing a batch of uploaded invoices. Invoice #4 is corrupt or empty. Should the program crash and abandon the rest? No, you want to skip invoice #4 and proceed directly to #5.
- You are drafting a new loop or function, but have not written the internal logic yet.
Python provides four specialized keywords to manipulate and fine-tune loop execution:
break: The emergency exit—terminates the loop instantly.continue: The skip button—aborts the current iteration and advances to the next one.pass: The placeholder—does absolutely nothing, fulfilling indentation syntax.else: The completion clause—runs code only if the loop completed naturally without hitting abreak.
1. The break Statement: Emergency Exit
The break statement terminates the enclosing loop immediately. Execution skips past all remaining iterations and resumes at the first line of code following the loop block.
Example: Stopping a Search Early
fruits = ["apple", "banana", "cherry", "durian", "elderberry"]
target = "cherry"
for fruit in fruits:
print(f"Checking {fruit}...")
if fruit == target:
print(f"--> Target '{target}' found! Halting search.")
break
print("Search operation concluded.")
Output:
Checking apple...
Checking banana...
Checking cherry...
--> Target 'cherry' found! Halting search.
Search operation concluded.
Notice that "durian" and "elderberry" were never checked. As soon as break fired, the loop stopped dead in its tracks.
break in while True Loops
A very common programming idiom is creating an intentional infinite loop with while True:, using break to exit once a specific condition or user command is met:
# Simulated user input prompt
commands = ["help", "status", "quit", "reload"]
index = 0
while True:
cmd = commands[index]
index += 1
print(f"Received user command: '{cmd}'")
if cmd == "quit":
print("Exit signal received. Terminating session...")
break
print("Application safely stopped.")
Output:
Received user command: 'help'
Received user command: 'status'
Received user command: 'quit'
Exit signal received. Terminating session...
Application safely stopped.
[!WARNING]
breakonly exits the innermost loop that contains it. If you have nested loops (a loop inside a loop), breaking inside the inner loop leaves the outer loop running.
2. The continue Statement: The Skip Button
Unlike break, which destroys the loop entirely, continue simply aborts the current iteration. Python discards any remaining code in the loop body for that cycle and jumps immediately to the next iteration.
Example: Processing Only Valid Data
transactions = [120.0, -15.5, 340.0, 0.0, -50.0, 89.9]
print("Processing valid deposits:")
for amount in transactions:
# Skip negative numbers and zero
if amount <= 0:
continue
print(f" Crediting account: +${amount:.2f}")
Output:
Processing valid deposits:
Crediting account: +$120.00
Crediting account: +$340.00
Crediting account: +$89.90
Flattening Code with Guard Clauses
Without continue, developers often write deeply nested if statements:
# Deep nesting (hard to read)
for item in items:
if item is not None:
if item.is_active:
if item.has_permission:
process(item)
# Clean, readable guard clauses using continue (Pythonic!)
for item in items:
if item is None:
continue
if not item.is_active:
continue
if not item.has_permission:
continue
process(item)
Using continue as a guard clause keeps your main business logic cleanly left-aligned rather than deeply indented.
3. The pass Statement: The Syntax Placeholder
In Python, indentation defines code blocks. If you write an if statement or loop with an empty body, Python will crash with an IndentationError: expected an indented block.
The pass keyword is a null operation (a “no-op”). When Python encounters pass, it does literally nothing. It simply satisfies Python’s grammar requirements:
# Valid Python: pass acts as an empty placeholder
for num in range(5):
if num == 2:
# TODO: Handle special event for number 2 in future release
pass
else:
print(f"Standard number: {num}")
Output:
Standard number: 0
Standard number: 1
Standard number: 3
Standard number: 4
Common uses of pass:
- Stubbing empty functions or classes during initial architectural design.
- Ignoring specific exceptions in
try ... exceptblocks.
4. The Pythonic Unique: The Loop else Clause
Most programmers know else from if ... else. But Python has a unique, powerful feature: loops can have an else clause too!
for item in sequence:
if condition:
break
else:
# Runs ONLY if the loop never hit a `break`!
Mental Model: Think “No-Break Victory Lap”
The name else on a loop often confuses newcomers. It helps to think of it as:
“Run this block if the loop ran to completion without hitting any
breakstatement.”
Practical Example: Prime Number Finder
A number is prime if it is greater than 1 and cannot be divided evenly by any number other than 1 and itself:
candidate = 13
# Check if candidate is divisible by any number from 2 up to candidate - 1
for divisor in range(2, candidate):
if candidate % divisor == 0:
print(f"{candidate} is NOT prime (divisible by {divisor}).")
break
else:
# If the loop finished checking all divisors without hitting break:
print(f"{candidate} IS a prime number!")
Output:
13 IS a prime number!
If candidate = 9:
- When
divisor = 3,9 % 3 == 0evaluates toTrue. - Python prints
"9 is NOT prime (divisible by 3)"and executesbreak. - Because the loop broke early, the
elseblock is skipped entirely!
Without the loop else construct, you would have had to invent an auxiliary tracking variable:
# The clumsy non-Pythonic flag variable pattern:
is_prime = True
for divisor in range(2, candidate):
if candidate % divisor == 0:
is_prime = False
break
if is_prime:
print(f"{candidate} IS prime!")
Python’s loop else eliminates this boilerplate flag variable cleanly.
5. Loop Control Comparison Table
| Keyword | What it does | What happens next |
|---|---|---|
break | Aborts the entire enclosing loop | Jumps to code immediately following the loop block |
continue | Skips the rest of current cycle | Jumps to next iteration (evaluates condition / next item) |
pass | Does nothing (syntax placeholder) | Continues executing the next line inside the same block |
Loop else: | Completion block | Executes only if the loop finishes naturally without break |
Summary & Stage 4 Review
Over Stage 4: Control Flow, you have mastered:
- Decision branching with if, elif, and else.
- Structural deconstruction and pattern matching with match-case.
- Automated repetition with for and while loops.
- Fine-grained iteration control using
break,continue,pass, andelse.
With the power to control your code’s path and repeat operations at will, you are ready to dive into storing and organizing structured data in Stage 5, starting with lists.