Break, Continue & Pass πΒΆ
Prerequisites: Python Loops
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) β