Welcome to Day 11 of the 100 Days of Python series!
Yesterday, we explored for
loops and the range()
function. Today, we’ll take things a step further and learn how to control the flow inside loops using three powerful tools: break
, continue
, and pass
.
These commands let you:
- Stop a loop (
break
) - Skip a specific iteration (
continue
) - Use a placeholder for future code (
pass
)
Let’s break it down (pun intended). 🧠
📦 What You’ll Learn
- What
break
,continue
, andpass
do in loops - When to use each control statement
- Real-world examples of each
- Common pitfalls
🛑 1. break
— Stop the Loop Immediately
The break
statement terminates the loop it's in — even if there are more iterations remaining.
🔸 Example:
for number in range(1, 10): if number == 5: break print(number)
Output:
1 2 3 4
As soon as number
becomes 5, the loop breaks.
✅ Use break
when:
- You want to exit a loop early
- You’ve found what you’re looking for
⏭️ 2. continue
— Skip to the Next Iteration
The continue
statement skips the rest of the code inside the loop for the current iteration and jumps to the next iteration.
🔸 Example:
for number in range(1, 6): if number == 3: continue print(number)
Output:
1 2 4 5
When number == 3
, Python skips the print()
.
✅ Use continue
when:
- You want to skip certain values
- You want to avoid executing some code under specific conditions
🚧 3. pass
— Do Nothing (Placeholder)
The pass
statement does nothing — literally. It’s used as a placeholder when you want to write syntactically correct code but haven't implemented it yet.
🔸 Example:
for number in range(1, 6): if number == 3: pass # Do nothing (for now) print(number)
Output:
1 2 3 4 5
Unlike continue
, pass
does not skip the iteration — it just silently stands in place.
✅ Use pass
when:
- You’re writing code ahead of time
- You need to define empty functions, classes, or blocks
🔁 Combined Example
for number in range(1, 10): if number == 3: print("Skipping 3") continue elif number == 5: print("Breaking at 5") break elif number == 7: pass # Placeholder — do nothing print(f"Number is: {number}")
Output:
Number is: 1 Number is: 2 Skipping 3 Number is: 4 Breaking at 5
🧠 Real-World Use Cases
🔍 Searching for an Item
items = ["apple", "banana", "cherry", "grape"] for item in items: if item == "cherry": print("Found cherry!") break
📋 Skipping Invalid Data
numbers = [5, 0, -3, 8, -1] for num in numbers: if num < 0: continue print("Processing:", num)
🧪 Stubbing Future Code
def handle_user_input(): # To be implemented later pass
⚠️ Common Mistakes
- Using
pass
when you actually meancontinue
- Forgetting to update loop variables in
while
loops (can cause infinite loops) - Misplacing
break
, which might skip essential code
🚀 Recap
Today you learned:
- ✅
break
: exit a loop early - ⏭️
continue
: skip the rest of the current iteration - 🚧
pass
: placeholder that does nothing - Real-life examples of loop control
Top comments (0)