Loop Control: break, continue, and else with Loops
Fine-tune loop behavior using statements that skip steps or stop execution early when targets are found.
What is it?
• `break`: Terminates the loop immediately. • `continue`: Skips the remainder of the current iteration and jumps to the next. • `else` with loops: A unique Python feature—executes ONLY if the loop finishes naturally without encountering a `break`!
Why is it used?
Improves execution speed during searches by stopping once the target is located, and cleanly handles 'item not found' logic.
Detailed Explanation
The `for...else` construct is idiomatic Python. Normally, developers set a boolean flag `found = False`, search in a loop, set `found = True; break;`, and check `if not found:`. With Python's `else:`, you place the 'not found' code directly in the loop's `else` block!
Syntax Structure
Syntax Blueprint
for item in collection:
if target:
break
else:
print("Target not found")
Code Example
PYTHON Code
# Searching for a Course in Database
catalog = ["Advanced Excel", "Data Analytics", "KLiC Python", "Web Development"]
search_query = "KLiC Python"
# Using break and loop else
for course in catalog:
if search_query.lower() in course.lower():
print(f"[FOUND] Matching course: '{course}'")
break # Stop searching
else:
print(f"[NOT FOUND] No course matched '{search_query}'")
# Using continue to skip inactive items
print("\n=== Processing Active Accounts ===")
users = [
{"name": "Aditya", "active": True},
{"name": "Sunil", "active": False}, # Suspended
{"name": "Neha", "active": True}
]
for u in users:
if not u["active"]:
continue # Skip inactive users
print(f"Sending newsletter email to: {u['name']}")
Explanation of the Code
• Loop breaks as soon as 'KLiC Python' matches, skipping remaining items.
• If no match occurred, the `else` block would trigger.
• `continue` bypasses the newsletter dispatch for inactive accounts.
Expected Output
[FOUND] Matching course: 'KLiC Python'
=== Processing Active Accounts ===
Sending newsletter email to: Aditya
Sending newsletter email to: Neha
Real-World Application
Used in search algorithms, prime number checkers, and automated data cleaning pipelines.
Common Mistakes to Avoid
• Misunderstanding the `else` block on loops (it does NOT run if the loop exits via `break`).
• Accidentally placing code after a `break` statement inside the loop (it will never execute).
Quick Practice Challenge
Write a loop from 1 to 10 that skips 5 using `continue` and prints all other numbers.
Key Takeaways
• `break` exits the loop immediately.
• `continue` skips the rest of the current iteration.
• Loop `else` runs only if the loop completed without encountering a `break`.