Break, Continue, and Pass in Python

 

What are Break, Continue, and Pass? 

Python gives us three special keywords to control loops: break, continue, and pass. These help us manage how our loops behave when we need something extra special to happen! 

Keyword What It Does
break Stops the loop immediately 
continue Skips the rest of the loop iteration and moves to the next one 
pass Does absolutely nothing! It's just a placeholder 

The break Statement 

Use break when you want to escape from a loop early. Imagine you’re at an all-you-can-eat buffet, but after 3 plates, you’re too full!  That’s when you leave (or "break") the loop!

for plate in range(1, 10):
    print(f"Eating plate {plate}")
    if plate == 3:
        print("Too full! Stopping here. ")
        break

Real-life Example:

  • You’re looking for chocolate in a bag of candies, and you stop as soon as you find one 
candies = ["Lollipop", "Gum", "Chocolate", "Caramel"]
for candy in candies:
    if candy == "Chocolate":
        print("Found chocolate! Stopping now!")
        break
    print(f"Skipping {candy}...")

The continue Statement 

Use continue when you want to skip the rest of the current loop iteration and move to the next one. Imagine you’re eating a mixed fruit salad, but you want to skip the raisins! 

fruits = ["Apple", "Banana", "Raisin", "Orange"]
for fruit in fruits:
    if fruit == "Raisin":
        print("Skipping the raisin!")
        continue
    print(f"Eating {fruit}")

Real-life Example:

  • You're counting numbers except for 5, which you want to skip! 
for number in range(1, 8):
    if number == 5:
        print("Skipping 5! ")
        continue
    print(f"Number: {number}")

 The pass Statement 

Use pass when you need a placeholder for future code. Imagine planning a party but not knowing the dessert yet—so you just write "TBD". 

def my_function():
    pass  # I’ll write this later!

🎭 Real-life Example:

  • You’re going through a to-do list, but some tasks aren’t ready yet!
tasks = ["Laundry", "Dishes", "Rocket Science"]
for task in tasks:
    if task == "Rocket Science":
        pass  # Not today, NASA! 
    else:
        print(f"Doing {task} ")

Summary 

Keyword Purpose
break Stops the loop immediately 
continue Skips the rest of the loop iteration 
pass Does nothing (useful as a placeholder) 

Now you’re a loop-controlling ninja! Try these in your own code and see how they make your loops smarter! 

 

Post a Comment

0 Comments