Breaking Free
Hoppy is running through a tunnel, but he spots a cave-in ahead! He needs to stop running immediately.
The break statement allows you to exit a loop early, even if the loop wasn't finished yet.
The Eject Button
You can put an if statement inside a loop. If the condition is met, break stops the loop instantly.
for i in range(100):
print(i)
if i == 3:
print("Stop!")
break
This loop was supposed to run 100 times, but it stopped at 3.
Your Mission
Write a for loop that runs 10 times (range(10)).
Inside the loop, print i.
Inside the loop, write an if statement to check if i == 5.
Inside the if, print "Trap found!" and then use break.
Python loops can have an else block too! It runs only if the loop finishes without hitting a break.
Suggested SolutionClick to expandClick to collapse
Escape plan:
for i in range(10):
print(i)
if i == 5:
print("Trap found!")
breakAdvanced TipsWant more? Click to expandClick to collapse
Programmers often write while True: (an infinite loop) and use break inside it to decide when to stop. This gives more control than a simple condition.