A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://realpython.com/python-break/ below:

How to Exit Loops Early With the Python Break Keyword – Real 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:

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.

Get Your Code: Click here to download the free sample code that shows you how to exit loops early with the Python break keyword.

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:

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:

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 5, a break statement terminates the loop early. So, this code will print the numbers from 0 to 4, 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:

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. pass_score, the variable that stores the threshold for passing a test, 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:

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:

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:

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:

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.

Using break Together With an else Clause

Python’s for and while loops have an else clause. This is an unusual feature that’s not present in many other programming languages. The else clause triggers if you don’t hit a break statement inside the loop.

The main use case of the else clause is to avoid variables that only keep track of whether you use break to end a loop. For example, you can rewrite the previous tutoring example with an else clause in your for loop:

Note that else is indented to line up with for. The break statement triggers if the student needs tutoring. In this case, the else clause is ignored. If the loop completes without hitting break, then the code under else is executed.

In this example, you don’t need the needs_tutoring variable from earlier as you use the control flow features in Python instead.

You can also use break and else to completely break out of nested for loops. Look back at the example with multiple students. Say that you’re only interested in whether any of your students failed at least one of the tests. You can use the following code:

Here you use an elsecontinuebreak construction that allows you break out of both for loops. If you break out of the inner loop, then you’ll hit the second break to terminate the outer loop as well. If you don’t execute break in the inner loop, then continue makes sure that you don’t execute break in the outer loop either.

This construction is a bit convoluted, and there are often better and more readable options available. In this example, you could instead flatten the nested lists and use a single loop to process the scores.

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.

Get Your Code: Click here to download the free sample code that shows you how to exit loops early with the Python break keyword.

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:


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4