- The break statement — how to exit a loop completely
- The continue statement — how to skip an iteration
- The else clause — what happens when a loop completes normally
- When to use each — choosing the right control statement
- Real-world examples — practical applications
- Common mistakes — and how to avoid them
Welcome: Why Loop Control Matters
Think of it this way: Imagine you're searching for a book in a library. You look at each shelf one by one. When you find the book, you stop searching — you don't keep looking at the remaining shelves. That's what break does. If you find a book that's damaged, you skip it and move to the next one — that's continue. And if you've checked every single shelf and didn't find the book, you might go to the front desk — that's the else clause.
Python provides three powerful tools to control loops: break, continue, and else. Each serves a different purpose and helps you write cleaner, more efficient code. Whether you're searching for data, filtering items, or handling errors, these statements are essential for every Python programmer.
💡 Key insight: break and continue work in both for and while loops. The else clause is a unique Python feature that runs only when the loop completes without a break.
The break Statement
Exiting a Loop Completely
The break statement immediately exits the loop, regardless of the loop condition.
# Example 1: Stop when you find what you're looking for
numbers = [1, 3, 5, 7, 8, 9, 11]
print("Searching for even number:")
for num in numbers:
print(f"Checking {num}...")
if num % 2 == 0:
print(f"Found an even number: {num}")
break
# Output:
# Checking 1...
# Checking 3...
# Checking 5...
# Checking 7...
# Checking 8...
# Found an even number: 8
# Example 2: Stop after a certain condition
count = 0
while True:
print(f"Count: {count}")
count += 1
if count == 5:
break
# Output: Count: 0, 1, 2, 3, 4
When to use break:
- When you've found what you're looking for
- When you need to stop a loop early based on a condition
- When you want to exit an infinite loop
- When you're processing data and a condition is met
✅ Quick Check: What does break do? (Answer: It exits the loop completely)
The continue Statement
Skipping an Iteration
The continue statement skips the rest of the current iteration and moves to the next one.
# Example 1: Skip even numbers
for i in range(10):
if i % 2 == 0:
continue
print(i)
# Output: 1 3 5 7 9
# Example 2: Skip numbers divisible by 3
for i in range(1, 11):
if i % 3 == 0:
continue
print(i)
# Output: 1 2 4 5 7 8 10
# Example 3: Skip invalid input
while True:
user_input = input("Enter a number (or 'exit'): ")
if user_input == "exit":
break
if not user_input.isdigit():
print("That's not a number! Try again.")
continue
print(f"You entered: {int(user_input)}")
When to use continue:
- When you want to skip certain items in a loop
- When you need to filter out invalid data
- When you want to avoid nested conditions
- When you want to keep the loop running but skip specific cases
✅ Quick Check: What does continue do? (Answer: It skips the rest of the current iteration and moves to the next one)
The else Clause in Loops
What Happens When a Loop Completes Normally
The else clause runs only when the loop completes without hitting a break statement.
# Example 1: For loop with else
print("Searching for 5:")
for i in range(1, 4):
if i == 5:
print("Found 5!")
break
else:
print("5 not found!")
# Output: 5 not found!
# Example 2: While loop with else
count = 0
while count < 3:
print(f"Count: {count}")
count += 1
else:
print("Loop completed normally!")
# Output:
# Count: 0
# Count: 1
# Count: 2
# Loop completed normally!
# Example 3: Finding a prime number
num = 17
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
print(f"{num} is not prime")
break
else:
print(f"{num} is prime")
# Output: 17 is prime
When to use else:
- When you need to check if a loop completed without a
break - When you're searching and want to know if something was found
- When you need to handle "not found" cases cleanly
- When you want to avoid using flag variables
✅ Quick Check: When does the else clause in a loop run? (Answer: When the loop completes without a break)
Break vs Continue vs Else
Comparing the Three Statements
Here's a quick comparison to help you remember when to use each:
break
- Exits the loop
- Stops all iterations
- Used when you found what you want
- Used in infinite loops
continue
- Skips current iteration
- Continues to next iteration
- Used to skip certain items
- Used for filtering
else
- Runs after loop ends
- Only if no break occurred
- Used for "not found" cases
- Used for completion checks
# Visual comparison
print("--- BREAK ---")
for i in range(5):
if i == 3:
break
print(i)
# Output: 0 1 2
print("--- CONTINUE ---")
for i in range(5):
if i == 3:
continue
print(i)
# Output: 0 1 2 4
print("--- ELSE ---")
for i in range(3):
print(i)
else:
print("Loop completed!")
# Output: 0 1 2 Loop completed!
✅ Quick Check: Which statement exits the loop completely? (Answer: break)
Real-World Examples
Practical Applications
💡 Example 1: Password Validation
# Keep asking until user enters a valid password
while True:
password = input("Enter password (min 8 chars): ")
if len(password) >= 8:
print("Password accepted!")
break
else:
print("Password too short. Try again.")
💡 Example 2: Processing Student Scores
# Process scores and find first failing student
scores = [85, 92, 78, 55, 90, 88]
found_failing = False
for score in scores:
if score < 60:
print(f"Failing student found: {score}")
found_failing = True
break
else:
print("All students passed!")
if found_failing:
print("A student needs extra help.")
💡 Example 3: Menu System with Input Validation
# Menu system that handles invalid input
while True:
print("\n1. View Data")
print("2. Add Data")
print("3. Delete Data")
print("4. Exit")
try:
choice = int(input("Choose: "))
except ValueError:
print("Please enter a valid number!")
continue
if choice == 4:
print("Goodbye!")
break
elif choice == 1:
print("Data displayed.")
elif choice == 2:
print("Data added.")
elif choice == 3:
print("Data deleted.")
else:
print("Invalid choice. Try again.")
✅ Quick Check: In the menu example, what happens if the user enters "exit"? (Answer: The break statement exits the loop)
Common Mistakes to Avoid
Watch Out For These!
❌ Mistake 1: Using break in the Wrong Place
If you put break outside a loop, you'll get a SyntaxError:
# WRONG
for i in range(5):
print(i)
break # SyntaxError! 'break' outside loop
# CORRECT
for i in range(5):
if i == 3:
break
print(i)
❌ Mistake 2: Confusing break and continue
They're different! break exits the loop; continue skips the current iteration:
# Wrong expectation
for i in range(5):
if i == 2:
continue
print(i)
# Output: 0 1 3 4 (skips 2, doesn't stop)
# Right expectation
for i in range(5):
if i == 2:
break
print(i)
# Output: 0 1 (stops at 2)
❌ Mistake 3: Not Understanding else in Loops
The else runs only if the loop completes without a break:
# WRONG assumption
for i in range(3):
if i == 1:
break
else:
print("Loop ended")
# Output: (nothing) — else doesn't run because break occurred
# CORRECT understanding
for i in range(3):
print(i)
else:
print("Loop ended")
# Output: 0 1 2 Loop ended
✅ Quick Check: What happens to the else block when a break occurs? (Answer: The else block doesn't run)
Try It Yourself!
Experiment with break, continue, and else directly in your browser. Modify the code and see the results in real time.
BREAK, CONTINUE, ELSE - PRACTICE
========================================
1. BREAK EXAMPLE
0 1 2 (loop stopped at 3)
2. CONTINUE EXAMPLE
0 1 2 4 (skipped 3)
3. ELSE EXAMPLE
0 1 2 (loop completed)
4. BREAK + ELSE
0 1 2
✅ Explore loop control!
🎉 You've Mastered Loop Control Statements!
You understand break, continue, and else in loops. These are essential tools for writing efficient, clean Python code!
Quick Quiz – Test Your Knowledge
Let's see what you've learned about loop control statements:
break statement do?continue statement do?else clause in a loop run?for i in range(5): if i == 2: continue; print(i)?Frequently Asked Questions
🤔 Can I use break and continue together?
break and continue in the same loop. continue skips the current iteration, and break exits the loop entirely. They serve different purposes and can be used together.
🔧 Does else work in while loops too?
else clause works in both for and while loops. It runs when the loop condition becomes False (for while) or when the sequence is exhausted (for for) — as long as no break occurred.
📐 What's the difference between pass and continue?
pass does nothing — it's a placeholder. continue skips the rest of the current iteration and moves to the next one. pass is used when you need a statement syntactically but don't want to execute anything.
📊 Can I break out of multiple nested loops?
break statement only exits the innermost loop. To break out of multiple nested loops, you can use a flag variable, wrap the loops in a function and use return, or use a for-else construct with a flag.
⚡ Is using else in loops considered Pythonic?
else clause in loops is a Python-specific feature and is considered Pythonic. It's a clean way to handle "not found" cases and avoids using flag variables. However, some developers find it confusing, so use it when it makes your code clearer.
🎯 What's the best practice for using these statements?
break to exit loops early when you've found what you need. Use continue to skip invalid or unwanted items. Use else to handle cases where the loop completes without a break. Keep your code simple and avoid using break and continue excessively.
📚 Where to Go From Here
Now that you've mastered break, continue, and else in loops, here are the next topics to explore:
🔄 For vs While
Understand the differences between for and while loops.
Learn More →📝 All Loops Assignments
Practice all loop concepts with hands-on assignments.
Practice →🔄 While Loop
Review the basics of while loops.
Review →