Break the Loop (When You Must)
Explore how to control loop execution in Python using break to stop loops when a condition is met and continue to skip values. This lesson teaches you to manage infinite loops and handle user input efficiently, helping you build interactive and responsive programs.
We'll cover the following...
Sometimes, we don’t want to run the entire code—just part of it—until a certain condition is met, like a user typing “quit” or a robot reaching a goal.
This is where Python gives us control tools like if statements to check conditions, and break to stop a loop immediately when needed.
It’s like saying: “Keep going… until this happens—then stop!”
Stopping a loop when a condition is met
In the example, we use a while True loop to keep asking the user for input until they type "exit." Then, we use a break to stop the loop.
while True:
answer = input("Type 'exit' to quit: ")
if answer == "exit":
break
print("You typed:", answer)Line 1:
while True:creates a loop that never stops on its own—it runs forever unless we manually break out of it.Line 2:
input("Type 'exit' to quit: ")asks the user to type something and stores it in the variableanswer.Line 3:
if answer == "exit":checks if the user typed"exit".Line 4:
breakimmediately stops the loop if the condition is met.Line 5:
print("You typed:", answer)only runs if the loop continues—so it shows what the user typed (unless it was"exit").
This pattern is common when we don’t know how many times a loop should run—we just wait for a certain input or event to stop it.
We now know how to break out of a loop whenever we want!
How it works
while True:creates an infinite loop.breakstops the loop early if a condition is met.This pattern is useful for menus, games, and interactive programs.
Skipping specific values in a loop
The continue keyword lets us skip the rest of the current loop and go straight to the next round.
We have used continue to skip the number 2 and go straight to the next iteration.
Use continue when you want to ignore certain values or conditions but keep looping.