🐸

Breaking Free

Python Basicspython-basics-21-breaking-free
Reward: 100 XP
|

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

1
Run

Write a for loop that runs 10 times (range(10)).

2
Check

Inside the loop, print i.

3
Spot Danger

Inside the loop, write an if statement to check if i == 5.

4
Escape

Inside the if, print "Trap found!" and then use break.

Loop Else

Python loops can have an else block too! It runs only if the loop finishes without hitting a break.

Suggested Solution
Click to expand

Escape plan:

for i in range(10):
  print(i)
  if i == 5:
      print("Trap found!")
      break
Advanced Tips
Want more? Click to expand

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.

pymain.py
Loading...
Terminal
Terminal
Ready to run...