How to Exit Loops Early With the Python Break Keyword

How to Exit Loops Early With the Python Break Keyword

by Dorothy Phoenix Apr 16, 2025 basics python

In Python, the break statement lets you exit a loop prematurely, transferring control to the code that follows the loop. This tutorial guides you through using break in both for and while loops. You’ll also briefly explore the continue keyword, which complements break by skipping the current loop iteration.

By the end of this tutorial, you’ll understand that:

  • A break in Python is a keyword that lets you exit a loop immediately, stopping further iterations.
  • Using break outside of loops doesn’t make sense because it’s specifically designed to exit loops early.
  • The break doesn’t exit all loops, only the innermost loop that contains it.

To explore the use of break in Python, you’ll determine if a student needs tutoring based on the number of failed test scores. Then, you’ll print out a given number of test scores and calculate how many students failed at least one test.

You’ll also take a brief detour from this main scenario to examine how you can use break statements to accept and process user input, using a number-guessing game.

Take the Quiz: Test your knowledge with our interactive “How to Exit Loops Early With the Python Break Keyword” quiz. You’ll receive a score upon completion to help you track your learning progress:


Interactive Quiz

How to Exit Loops Early With the Python Break Keyword

In this quiz, you'll test your understanding of the Python break statement. This keyword allows you to exit a loop prematurely, transferring control to the code that follows the loop.

Introducing the break Statement

Before proceeding to the main examples, here’s a basic explanation of what the break statement is and what it does. It’s a Python keyword that, when used in a loop, immediately exits the loop and transfers control to the code that would normally run after the loop’s standard conclusion.

You can see the basics of the break statement in a simple example. The following code demonstrates a loop that prints numbers within a range until the next number is greater than 5:

Python
>>> for number in range(10):
...     if number > 5:
...         break
...     print(number)
... 
0
1
2
3
4
5

This short code example consists of a for loop that iterates through a range of numbers from 0 to 9. It prints out each number, but when the next number is greater than 5, a break statement terminates the loop early. So, this code will print the numbers from 0 to 5, and then the loop will end.

As break statements end loops early, it wouldn’t make sense for you to use them in any context that doesn’t involve a loop. In fact, Python will raise a SyntaxError if you try to use a break statement outside of a loop.

A key benefit of using break statements is that you can prevent unnecessary loop iterations by exiting early when appropriate. You’ll see this in action in the next section.

Breaking Out of a Loop With a Set Number of Iterations

Imagine you’re a teacher who evaluates the scores of your students. Based on the scores, you want to determine how many tests each student has failed. The following example demonstrates how you might accomplish this task using a for loop to iterate through the students’ test scores:

Python
>>> scores = [90, 30, 50, 70, 85, 35]

>>> num_failed_scores = 0
>>> failed_score = 60
>>> for score in scores:
...     if score < failed_score:
...         num_failed_scores += 1
...
>>> print(f"Number of failed tests: {num_failed_scores}")
Number of failed tests: 3

You start with a list of scores for one student. Before the loop runs, you set a few variables. The variable num_failed_scores is set at 0, because you haven’t yet found any failing scores. failed_score, the variable that stores the threshold failure score, is set at 60, so any score less than that is considered a failed test.

As the for loop begins, it will run as many times as there are scores in the list, iterating over each score. If the score is less than the failing score threshold, it increments the num_failed_scores variable by 1. Finally, you output the number of tests that the student failed.

To support students who underperform, you decide to implement a tutoring system. Once a student has failed two tests, you want to propose tutoring to them. In this case, you don’t need to loop through all the scores. The moment a student has failed two tests, you’ve gained the information needed and can stop the iteration. Here’s how your adjusted code might look in this case, using a break statement:

Python
>>> scores = [90, 30, 50, 70, 85, 35]

>>> num_failed_scores = 0
>>> failed_score = 60
>>> needs_tutoring = "No"
>>> for score in scores:
...     if score < failed_score:
...         num_failed_scores += 1
...     if num_failed_scores >= 2:
...         needs_tutoring = "Yes"
...         break
...
>>> print(f"Does the student need tutoring? {needs_tutoring}")
Does the student need tutoring? Yes

As before, you start with a list of scores for one student. Before the loop runs, you set a few variables. The code is pretty much the same but with a few additions. Before the loop, you add a new variable, needs_tutoring, which is initially set to "No" because you haven’t yet recommended tutoring for this student.

You still iterate through the scores and increment the num_failed_scores variable if the loop finds a failed test score. Next, in a new step after checking each score, the loop will check to see if there are at least two failed scores. If so, the code sets the needs_tutoring variable to "Yes", and the loop exits early with a break statement. Finally, the code displays a message indicating whether or not the student needs tutoring.

So far, you’ve seen the break statement paired with for loops. As you’ll see in the next section, you can also use it with while loops.

Using the Python break Statement to Process User Input

When you need to get input from a user, you’ll often use a loop but you won’t always know how many iterations your loop will need. In these cases, a while loop is a good choice, and you can pair it with a break statement to end the loop when you’re finished getting the user’s input.

Taking a slight detour from the student test scores example, you can also see this concept demonstrated in a number-guessing game. In this game, you give the player a limited amount of turns to guess a randomly generated number. The game loop, a while loop in this case, will run at least as many times as the number of turns, but it can end early.

At the start of each turn, you prompt the user to enter a number, or a quit character. If the player correctly guesses the number, you break out of the game loop and congratulate the player. If the player uses up all the turns without guessing the correct number, the game loop terminates and the code outputs the correct number.

If the player enters the quit character, the loop will use a break statement to exit the game early:

Python
>>> import random

>>> guesses_left = 4
>>> random_number = random.randint(1, 10)

>>> while True:
...     if guesses_left <= 0:
...         print(
...             "You ran out of guesses! "
...             f"The correct number was {random_number}"
...         )
...         break
...     guess = input("Guess a number between 1 and 10, or enter q to quit: ")
...     if guess == "q":
...         print("Successfully exited game.")
...         break
...     elif not (guess.isnumeric()):
...         print("Please enter a valid value.")
...     elif int(guess) == random_number:
...         print("Congratulations, you picked the correct number!")
...         break
...     else:
...         print("Sorry, your guess was incorrect.")
...         guesses_left -= 1
...         print(f"You have {guesses_left} guesses left.")
...
Guess a number between 1 and 10, or enter q to quit: 5
Sorry, your guess was incorrect.
You have 3 guesses left.
Guess a number between 1 and 10, or enter q to quit: 3
Sorry, your guess was incorrect.
You have 2 guesses left.
Guess a number between 1 and 10, or enter q to quit: 7
Sorry, your guess was incorrect.
You have 1 guesses left.
Guess a number between 1 and 10, or enter q to quit: 2
Sorry, your guess was incorrect.
You have 0 guesses left.
You ran out of guesses! The correct number was 8

At the beginning of the code, you import the random module in order to access Python’s random number generator functionality. Next, you set up some key variables for the game. First, you create a variable to store the number of guesses that the player has remaining. Then, you create a variable and store a random integer, between 1 and 10, inclusive, using Python’s randint() function.

The next segment of the code is the game loop. You set up a while loop with a sentinel condition of True. So, you’ll need a break statement to exit the loop—otherwise the loop will continue running indefinitely.

Inside the game loop, you first check to see if the player has any guesses left. If no guesses remain, then you print out a message informing the player that there are no guesses left and reveal the correct number. You then use break to break out of the game loop.

If the player still has guesses remaining, then you prompt the player to enter either a number between 1 and 10, or the character q to quit the game. You store the player’s response in the variable guess.

Next, you check the player’s response using a series of conditional statements. If the player enters the letter q to exit the game, you print out a message alerting the player that the game has ended, and you follow up with a break statement to exit the game loop.

To determine if the player entered a number, you use the .isnumeric() method. If the player’s response wasn’t a number, you again prompt the player to enter a valid value. Note that this check comes after you determine if the player entered the quit character, so at this point, any responses should be numeric.

If the player has correctly guessed the number, you print a congratulatory message to the screen, and then end the game loop with a break statement. However, if the player’s guess was incorrect, you print a message explaining that the guess was wrong. You then subtract one guess, and print out the remaining number of guesses. At this point, you have reached the end of the loop iteration, so the code will begin the next iteration.

This example also showcases another advantage of and common use case for the break statement. As you saw, you used the break statement to prevent the loop from running indefinitely. Using the break statement appropriately helps to ensure that you don’t end up with an infinite loop.

This while loop and break combination is a common pattern for getting user input, especially in situations where you don’t know how many times your loop will need to run before the user is finished.

For example, think of a chatbot that provides customer service assistance on a commerce site. The chatbot might continue prompting users to ask questions or for relevant information until all the users’ problems are solved. The chat could use a while loop that runs until the users indicate they no longer need assistance, at which point the loop can exit with a break statement.

Breaking Out of Nested Loops

You can also use break statements to exit nested loops. Used in this way, the break statement will terminate the innermost enclosing loop. Returning back to your student test score analysis tool, consider the following example to illustrate this principle.

In this example, your tool will examine test scores from multiple students to determine how many students received at least one failed test score. An outer loop will iterate through different lists of student scores, while an inner loop will iterate through the individual scores for each student list:

Python
>>> scores = [
...     [90, 30, 80, 100],
...     [100, 80, 95, 87],
...     [75, 84, 77, 50],
... ]

>>> failed_score = 60
>>> num_failed_students = 0
>>> for student_score_list in scores:
...     for score in student_score_list:
...         if score < failed_score:
...             num_failed_students += 1
...             break
...
>>> print(f"Number of students who failed a test: {num_failed_students}")
Number of students who failed a test: 2

You begin by creating a list of scores. This list actually contains three separate sublists, each representing one student’s test scores.

You then set up a couple of integer variables. First, you set the threshold for a failed test score, which is 60, as in the previous code example. Next, you set the initial number of students who failed a test to 0, because you haven’t found any failed test scores yet.

Next, you begin the code’s outer for loop. This loop will iterate through each of the three student score lists. Inside of that loop, you create a nested for loop that takes one student score list, and iterates through each of the individual scores.

If the inner loop finds a failed score, then you increment the number of students who have failed a test by 1, and then break out of that inner loop since there’s no need to check the rest of that student’s scores. Note that the break statement only exits the inner loop, and the code will continue with the next list of student scores as the outer loop continues.

At the end of the code, you output to the screen the number of students who have failed at least one test.

Using the continue Keyword Instead of break

Python also has another keyword that allows you to reduce the number of unnecessary loop iterations. The continue keyword lets you skip specific iterations of a loop if the given conditions are met. If an iteration meets the given conditions, then the loop will skip that iteration and move on to the next one.

For example, suppose you want to iterate over a range of numbers and print out only the odd numbers. You could write code with the continue keyword, like in the following example:

Python
>>> for index in range(6):
...     if index % 2 == 0:
...         continue
...     print(index)
...
1
3
5

This code sample will print out the numbers 1, 3, and 5. You create a for loop to iterative over the range of numbers 1 through 6. Inside the loop, you use the modulo operator to check each number in the range. If the remainder of the number divided by 2 is equal to 0, the number is even, so you’ll branch to a continue statement. This continue statement terminates the loop iteration, so the code after continue will not execute.

However, if the remainder of the number divided by 2 isn’t 0 (it should actually be 1, for odd numbers), then the code will not execute the continue statement. Instead, it will print out the number.

break and continue are similar in that they both end the current loop iteration. However, while break exits the innermost loop entirely, ending any further iterations, continue skips the rest of the current iteration and moves on to the next one. Both keywords are valuable tools for exiting a loop iteration early when necessary.

Conclusion

In this tutorial, you explored the break statement in Python and learned how to use it to exit loops early. You saw an example of a student test score analysis tool, which demonstrated how to prevent a loop from continuing after achieving the intended results, as well as how to exit a nested loop.

Through the number-guessing game example, you also learned how you can use break statements to take in and process user input. Then you took a brief look at the continue statement, a similar keyword that allows you to skip a single iteration of a loop.

Understanding break statements and how to terminate loops early is an essential Python skill, as it helps you write more efficient code by reducing unnecessary iterations and preventing problematic infinite loops.

Frequently Asked Questions

Now that you have some experience with the break statement in Python, you can use the questions and answers below to check your understanding and recap what you’ve learned.

These FAQs are related to the most important concepts you’ve covered in this tutorial. Click the Show/Hide toggle beside each question to reveal the answer.

You use the break statement in Python to immediately exit a loop, allowing the program to continue executing the code that follows the loop.

No, it doesn’t make sense to use break outside of loops because it’s specifically designed to exit loops.

No, the break statement only exits the innermost loop in which it’s used, not all encapsulating loops.

Take the Quiz: Test your knowledge with our interactive “How to Exit Loops Early With the Python Break Keyword” quiz. You’ll receive a score upon completion to help you track your learning progress:


Interactive Quiz

How to Exit Loops Early With the Python Break Keyword

In this quiz, you'll test your understanding of the Python break statement. This keyword allows you to exit a loop prematurely, transferring control to the code that follows the loop.

🐍 Python Tricks 💌

Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

Python Tricks Dictionary Merge

About Dorothy Phoenix

Dorothy is an independent video game developer, software engineer, technical writer, and tutor.

» More about Dorothy

Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

Master Real-World Python Skills With Unlimited Access to Real Python

Locked learning resources

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Level Up Your Python Skills »

Master Real-World Python Skills
With Unlimited Access to Real Python

Locked learning resources

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Level Up Your Python Skills »

What Do You Think?

Rate this article:

What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.

Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. Get tips for asking good questions and get answers to common questions in our support portal.


Looking for a real-time conversation? Visit the Real Python Community Chat or join the next “Office Hours” Live Q&A Session. Happy Pythoning!

Keep Learning

Related Topics: basics python

Related Tutorials: