Loop Control Statements
Overview
Control statements (break, continue, pass, else) allow you to change the flow of loops dynamically.
Learning Objectives
- Exit loops early using the break statement.
- Skip the rest of the current loop iteration using continue.
- Use the else clause to run code when loops complete naturally.
Concept Explanation
Use break to stop and exit a loop immediately. Use continue to skip the rest of the current iteration and jump straight to the next cycle check. The else block runs only if the loop finishes all iterations without hitting a break.
Code Examples
Example 1 — Basics
This example introduces the fundamental syntax and concepts.
for val in range(5):
if val == 3:
break
print(val)
Example 2 — Everyday Usage
This example demonstrates a realistic scenario handling business parameters.
# Print positive numbers only
prices = [10, -5, 20, -2, 15]
for p in prices:
if p < 0:
continue
print(f'Valid price: {p}')
Example 3 — Advanced Example
This example shows clean, production-grade code structure following senior development standards.
# Find element in a list; execute fallback code if missing
names = ['Alice', 'Bob', 'Charlie']
target = 'David'
for name in names:
if name == target:
print('Found target name!')
break
else:
print('Target name was not in the list.')
Visual Flow
The following execution flow represents the step-by-step evaluation inside the interpreter:
Iteration check → Hit control flag (break/continue) → Exit loop OR skip remaining block statements
Common Mistakes
Review these common pitfalls when working with this topic:
- Confusing continue with pass. pass does nothing, while continue skips to the next loop cycle.
- Expecting the loop else block to run when the loop is terminated by a break statement.
- Using break inside nested loops expecting it to exit all loops (it only exits the innermost loop).
- Placing code blocks directly below break statements inside the same block.
Best Practices
Enforce these Pythonic best practices in your codebase:
for x in items:
if is_target(x):
found = True
break
if not found:
print('Not found') # Redundant tracking flag
for x in items:
if is_target(x):
break
else:
print('Not found') # Native loop-else structure
Quick Revision
Use these key summaries for last-minute revision:
- break exits loops immediately.
- continue skips remaining statements and goes to next loop cycle.
- pass acts as a syntactic placeholder.
- loop else blocks run only if no breaks occurred.
- Control statements improve logic efficiency.