How to Exit Loops Early With the Python Break Keyword

How to Exit Loops Early With the Python Break Keyword

by Dorothy Phoenix 0 Comments 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

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Article

Already a member? Sign-In

Locked learning resources

The full article is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Article

Already a member? Sign-In

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:

What Do You Think?

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!

Become a Member to join the conversation.

Keep Learning

Related Topics: basics python