Break and Continue

STEP 2 — Break and continue (a.k.a. The Loop Drama Buttons)

OHOOOO smartie pants — STEP 2 IS HERE, and this is where loops stop being polite and start acting like they’ve had three espressos and a motivational speech from The Rock.

Let’s go full energy, full chaos, full “your code is now a beast.”

In Step 1, loops got stronger.

Now they get attitude.

Because sometimes your loop needs to say:

“STOP EVERYTHING!”

or

“Skip this nonsense and keep going.”

That’s where break and continue come in.


1. break — The Emergency Stop Button

break is your loop’s way of yelling:

“NOPE. I’m done. I’m out. Goodbye.”

It instantly stops the entire loop, even if there were more items left.

Example:

for enemy in ["slime", "goblin", "dragon", "orc"]:
    if enemy == "dragon":
        print("Dragon spotted! Retreat!")
        break
    print("Fighting:", enemy)

Your loop sees the dragon and immediately rage-quits.

Honestly? Relatable.

Click Run

2. continue — The “Skip This” Button

continue says:

“Yeah, not dealing with that. Next!”

It skips the current loop step but keeps the loop running.

Example:

for item in ["potion", "rock", "potion", "stick"]:
    if item == "rock":
        continue
    print("You pick up:", item)

Your loop refuses to pick up rocks.

Because rocks are boring.

Click Run

3. break vs. continue — The Vibe Check

Command What It Does
break Ends the loop completely
continue Skips one step and keeps looping

One is dramatic.

One is petty.

Both are useful.


Practice (Your Turn!)

Mini-Challenge

Loop through numbers 1 to 5.

  • If the number is 3, skip it.
  • If the number is 5, stop the loop.
Modify and Run

Your loop now behaves like a moody teenager.

Perfect.

You now control:

  • break → the emergency exit
  • continue → the skip button

Your loops can now make decisions mid-loop like they’re running a whole strategy meeting.

Ready for Step 3, where we unleash nested loops — loops inside loops, the coding equivalent of Inception.