Please enable JavaScript to use CodeHS

Python Tutorial

Break and Continue in Python

Loops don't have to run start to finish every time. With break you can exit a loop the instant you're done, and with continue you can skip a lap you don't want. Learn when to reach for each one.

python ~20 min Beginner friendly
The Big Idea

Two loop superpowers

Python has some nifty tools we can use to tweak the behavior of for loops and while loops. In this tutorial we'll learn about two of them: break and continue.

Picture your loop as a metro train visiting stations, one lap of the loop per station. Normally the train visits every station on the route. These two keywords change the ride:

break: end the ride

Exit the loop entirely, right now.

  • The rest of this lap is skipped
  • All remaining laps are skipped too
  • The program jumps to the first line after the loop

continue: skip one stop

Skip the rest of this lap, then keep looping.

  • The rest of this lap is skipped
  • The loop jumps straight back to its condition
  • Future laps still happen as usual

Both keywords live inside loops. They almost always show up inside an if statement, because you only want to break out or skip ahead when a specific condition is met.


Keyword 1

Break: exit the loop right now

The break statement lets us immediately exit a loop without executing any of the remaining code in the loop. The moment Python hits break, the loop is over. No finishing the current lap, no future laps.

At a high level, a break statement usually looks like this:

main.py
while condition:
    # code that runs each lap of the loop
    if some_condition:
        break  # immediately exits the loop
    # this code is skipped when the break happens

Think of it as a search-and-stop tool. Looking for one thing in a big pile? The instant you find it, there's no reason to keep looping. break lets you stop right there.

Break + While

Break in while loops

break statements work really well with while loops because they help us avoid repeated code. Look at this guessing game that asks the user to guess a secret number between 1 and 10. It works, but notice that lines 2 and 6 are exactly the same, because we need to get the user's guess before entering the while loop.

version_1.py
secret_num = 6
guess = int(input("Guess a number, 1-10: "))

while guess != secret_num:
    print("Wrong. Try again.")
    guess = int(input("Guess a number, 1-10: "))

print("You win!")
Console (one possible run)
Guess a number, 1-10: 3
Wrong. Try again.
Guess a number, 1-10: 9
Wrong. Try again.
Guess a number, 1-10: 6
You win!

The program below does the same job but uses a break statement. Instead of writing the input line twice, before and inside the loop, we write it once inside the loop:

version_2.py
secret_num = 6

while True:
    guess = int(input("Guess a number, 1-10: "))
    if guess == secret_num:
        print("You win!")
        break
    print("Wrong. Try again.")
Console (one possible run)
Guess a number, 1-10: 3
Wrong. Try again.
Guess a number, 1-10: 9
Wrong. Try again.
Guess a number, 1-10: 6
You win!

How does it work? We use while True as the loop condition, so the loop would repeat forever on its own. Then we move the exit condition, if guess == secret_num, onto the break statement. The loop keeps asking for input until the special "stop" value shows up. This ask-until-a-special-answer pattern is called looping until a sentinel value, and while True plus break is the classic way to write it.

Wait, isn't while True an infinite loop? It would be, except the break gives the loop a guaranteed exit. If you ever write while True, double-check that a reachable break is inside!

Experiment: what happens if you move print("You win!") to after the break statement? It never runs! Once break executes, nothing else in the loop body gets a turn.

Break + For

Break in for loops

You can also use the break statement in for loops, and it behaves exactly the same way: the loop ends immediately, even if range() had more values queued up. Look at the example below and try guessing what will happen before you run it!

main.py
for i in range(10):
    if i == 5:
        print("Exiting the loop now!")
        break
    print(i)
Console
0
1
2
3
4
Exiting the loop now!

Even though range(10) promised the values 0 through 9, the loop stops the moment i reaches 5. The numbers 5 through 9 never get printed. Some things to try:

  • Change the condition for the break statement. What happens with if i == 0?
  • What happens if you move the print(i) command to before the if statement? (Hint: does 5 get printed now?)

Keyword 2

Continue: skip this lap

While the break statement immediately exits the loop, the continue statement immediately jumps back to the top of the loop. The rest of this lap is skipped, but the loop itself keeps going with the next lap. That lets us skip specific iterations without exiting the entire loop.

The example below is exactly the same as the for loop above, except break has been swapped for continue. Guess what will happen before you run it!

main.py
for i in range(10):
    if i == 5:
        print("Returning to the top of the loop!")
        continue
    print(i)
Console
0
1
2
3
4
Returning to the top of the loop!
6
7
8
9

See the difference? The number 5 is missing, but the loop kept right on going: 6, 7, 8, and 9 all printed. continue skipped one single lap, the one where i was 5, and nothing else.

continue is your skip-the-bad-items tool. Looping through a list where some items shouldn't be processed? Use continue to hop over them and keep going.

In a while loop, continue jumps straight back to the condition check. Be careful: if the line that updates your condition variable comes after the continue, it gets skipped too, and you can accidentally create an infinite loop. In a for loop that can't happen, because Python moves to the next range() value for you.


Interactive

The Metro Simulator

Time to drive the train yourself. This loop, for i in range(1, 8), is a metro route with stations 1 through 7. Pick a rule station, pick a keyword, then press Run and watch how the ride changes. The code panel highlights the exact line Python is executing.

Rule if i == Keyword

            
Console
Choose a rule and a keyword, then press Run.

Run all three keywords with the same rule and compare the consoles. With break, the train never reaches the later stations. With continue, exactly one station goes missing from the printout. With neither, it's an ordinary loop that visits everything.


Compare

Break vs. continue at a glance

Both keywords interrupt the current lap of the loop. The difference is what happens next:

break continue
What it does Exits the loop entirely, right now. The program jumps to the first line after the loop. Skips the rest of this iteration only, then jumps back to the top of the loop for the next lap.
When to use it Search-and-stop jobs: you found what you were looking for, or the user typed the quit value, so there's no reason to keep looping. Skip-the-bad-items jobs: some values shouldn't be processed (like the unlucky number 13), but the loop should keep going.
In a while loop Ends the loop no matter what the condition says. Powers the classic while True: + break input pattern. Jumps straight back to the condition check. Anything after the continue in the body is skipped.
In a for loop Ends the loop even if range() has values left over. Moves on to the next range() value automatically.
Common bug Code placed after the break inside the loop body never runs, so a "You win!" placed below it never prints. In a while loop, skipping the line that updates the condition variable can cause an infinite loop.

One more rule they share: both keywords only affect the loop they are directly inside. In nested loops, break exits just the inner loop, and using either keyword outside of any loop is a syntax error.


Your Turn

Practice with break and continue

Try your hand at break and continue statements with these challenges. Each one has a solution you can peek at, but give it a real try first!

Level 1

Skip unlucky 13

Write a program that prints out the numbers 1 through 20 but skips the unlucky number 13.

solution.py
for i in range(1, 21):
    if i == 13:
        continue
    print(i)
Console
1
2
3
4
5
6
7
8
9
10
11
12
14
15
16
17
18
19
20

This is a skip job, so continue is the right tool. Note that range(1, 21) goes up to 20, because the end value is not included. What would happen if you used break here instead? The loop would stop at 12 and never print 14 through 20!

Level 2

Product until -1

Write a program that finds the product of a series of numbers the user enters and prints the result to the screen. Keep asking the user for a number until the user enters -1. Multiply each number the user enters and print the running product. Hint: you will need to store the product in a variable, and you can use int(input(prompt)) to get a number from the user.

solution.py
product = 1

while True:
    num = int(input("Enter a number (-1 to stop): "))
    if num == -1:
        break
    product = product * num
    print("Product so far: " + str(product))

print("Final product: " + str(product))
Console (one possible run)
Enter a number (-1 to stop): 2
Product so far: 2
Enter a number (-1 to stop): 5
Product so far: 10
Enter a number (-1 to stop): 4
Product so far: 40
Enter a number (-1 to stop): -1
Final product: 40

This is the sentinel pattern from the guessing game: while True keeps asking, and break fires when the special stop value (-1) appears. The product starts at 1, not 0, because multiplying by 0 would wipe everything out.

Level 3

Product with a limit

Extend your product program! Continue asking the user for a number until the user enters -1 or the product is greater than 200.

solution.py
product = 1

while True:
    num = int(input("Enter a number (-1 to stop): "))
    if num == -1:
        break
    product = product * num
    print("Product so far: " + str(product))
    if product > 200:
        print("The product got too big!")
        break

print("Final product: " + str(product))
Console (one possible run)
Enter a number (-1 to stop): 10
Product so far: 10
Enter a number (-1 to stop): 7
Product so far: 70
Enter a number (-1 to stop): 6
Product so far: 420
The product got too big!
Final product: 420

One loop can have more than one break! Here there are two ways out: the user types -1, or the product passes 200. Whichever condition happens first ends the loop.


Check Yourself

Quick quiz

1. What does this program print?

for i in range(5):
    if i == 3:
        break
    print(i)

2. You are looping through a list of test scores and want to ignore any score of -1 but keep grading the rest. Which keyword should you use?

3. In a while True: loop that asks for input, what stops it from looping forever?

Keep learning Python

Break exits a loop instantly, and continue skips a single lap. Now that you can steer your loops, go back and master the loops themselves, or jump into a full Python course.