Skip to content

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: break terminates the whole loop; continue only terminates the current iteration.

← Back: Loops | Next: Comparisons (For vs While) β†’