Break, Continue & Pass 🚀¶
Mentor's Note: Sometimes loops need to be interrupted. These three keywords are your "emergency brakes" and "navigation tools" for loops. 💡
🌟 The Scenario: The Gift Inspector 🎁¶
Imagine you are inspecting a line of 10 gift boxes.
- The Logic:
- BREAK: You find a Bomb 💣. Stop everything and run out of the building! (Jump out of loop). 📦
- CONTINUE: You find a Slightly Scratched box 📦. Ignore it and move to the next one. (Skip current turn). 📦
- PASS: You find a Gold box 🌟. You haven't decided what to do with it yet, so you just stand there for a second and then move on. (Placeholder). ✅
📖 Concept Explanation¶
1. break¶
Immediately stops the loop and moves to the next part of the program outside the loop.
2. continue¶
Stops the current "turn" (iteration) and jumps back to the top of the loop for the next turn.
3. pass¶
Does nothing! It's a null operation. Use it when Python syntax requires a line of code, but you aren't ready to write the logic yet.
🎨 Visual Logic: Control Flow comparison¶
graph LR
A[Start Turn] --> B{Action?}
B -- break --> C[Exit Loop 🛑]
B -- continue --> D[Next Turn ⏭️]
B -- pass --> E[Continue inside ⚙️]
💻 Implementation: Control Lab¶
# 🛒 Scenario: Searching for a specific number
# 🚀 Action: Using break and continue
print("Testing Loop Control:")
for num in range(1, 6):
if num == 3:
print("Found 3! Skipping it. ⏭️")
continue # Skips printing 3
if num == 5:
print("Reached 5. Stopping loop! 🛑")
break # Exits the loop entirely
print(f"Processing number: {num}")
def future_feature():
pass # 💡 Using pass as a placeholder for a new function
📊 Sample Dry Run¶
| Num | If (==3)? | If (==5)? | Action |
|---|---|---|---|
| 1 | No | No | Print "Processing 1" |
| 2 | No | No | Print "Processing 2" |
| 3 | Yes ✅ | -- | CONTINUE (Jumps to 4) |
| 4 | No | No | Print "Processing 4" |
| 5 | -- | Yes ✅ | BREAK (Loop Ends!) |
💡 Board Focus (CBSE/GSEB) 👔¶
- Important: Examiners love to ask: "What is the difference between break and continue?"
- Answer:
breakterminates the whole loop;continueonly terminates the current iteration.
← Back: Loops | Next: Comparisons (For vs While) →