Introduction
The Python break
statement allows you to prematurely exit a loop before its natural completion. This statement is handy when you want to stop a loop’s execution for a condition that is not convenient to check under the loop’s normal syntax. It can be used with both the for
and while
loops.
Basic break Statement Syntax
To break from a loop, all you need to do is write break
on its own line of code. It must be placed within a loop, which it will terminate. break
statements not placed inside loops cause a syntax error.
Since break
is useful for exiting a loop under a certain condition, it is often used within conditional statements, such as an if
.
Here’s the basic syntax of the Python break
statement with a for
loop:
for element in iterable: # possible code above if condition: break # possible code below
And here’s the basic syntax of break
with a while
loop:
while loop-condition: # possible code above if condition: break # possible code below
Using break With for Loops
for
loops iterate through all items in an iterable, and a break
statements are useful when there is an additional condition other than reaching the last item that necessitates ending the loop.
Example:
dogs = ["Scooby-Doo", "Snoopy", "Goofy", "Clifford", "Astro"] num_of_treats = 3 for dog in dogs: if num_of_treats == 0: break print(f"{dog} gets a treat. Woof!") num_of_treats -= 1
Output:
Scooby-Doo gets a treat. Woof! Snoopy gets a treat. Woof! Goofy gets a treat. Woof!
In the example above, a few cartoon dogs are given treats. However, the number of treats is limited, so not every dog may get one. The for
loop on line 4 iterates through the dog
list, and inside the loop, on line 7 each dog is given a treat. But if they run out, no more dogs will be given a treat anymore. This safeguard is kept by the break
statement on line 6. The if
statement on line 5 checks whether there are any more treats, and if the number of treats is 0, break
exits the loop, and no more treats are given. Sorry Clifford and Astro.
Using break with while Loops
In while
loops, break
statements are especially useful when the loop stopping condition is not known at the beginning of the iteration.
The following example also appears in the lesson about while
loops, and it’s a little program for squaring numbers the user inputs. The user can exit the program by typing ‘exit’ at the prompt. The user’s input of the string ‘exit’ is the loop stopping condition. It’s not known at the beginning of the loop on line 1, and therefore, the program uses an if
statement and a break
on lines 4 and 5 to exit the loop.
Example:
while True: user_input = input("Enter a number (or 'exit' to quit): ") if user_input.lower() == 'exit': break number = int(user_input) square = number ** 2 print(f"The square of {number} is {square}.") print("Goodbye.")
Output:
Enter a number (or 'exit' to quit): > 2 The square of 2 is 4. Enter a number (or 'exit' to quit): > 10 The square of 10 is 100. Enter a number (or 'exit' to quit):
Understanding the Python break Behavior in Nested Loops
When using a break
statement within nested loops, it only terminates the innermost loop where it is located.
In the next example, the goal of the program is to give dogs 3 treats each until the treats run out. Some dogs may get fewer than 3, or none at all. For instance, if Snoopy gets 3 treats, “Snoopy gets treat #1 #2 #3. Woof!” should be printed, but if he gets only 1 treat, “Snoopy gets treat #1. Woof!” is printed. If a dog receives no treats at all, nothing should be printed about that dog.
The following code attempts to implement this with nested loops and a break
statement, but there is a problem. For the last dog, Astro, we run out of treats, but instead of printing nothing, the program prints “Astro gets treat. Woof!”, which doesn’t make sense and is a mistake.
Example:
dogs = ["Scooby-Doo", "Snoopy", "Goofy", "Clifford", "Astro"] num_of_treats = 10 for dog in dogs: print(f"{dog} gets treat", end="") for i in range(3): if num_of_treats == 0: break print(f" #{i+1}", end="") num_of_treats -= 1 print(". Woof!")
Output:
Scooby-Doo gets treat #1 #2 #3. Woof! Snoopy gets treat #1 #2 #3. Woof! Goofy gets treat #1 #2 #3. Woof! Clifford gets treat #1. Woof! Astro gets treat. Woof!
The code in the above example has two nested for
loops. The outer loop, which starts on line 4, iterates through the dogs, and the inner loop, which starts on line 6, gives each dog 3 treats until they run out.
When the treats run out, the if
and break
statements on lines 7 and 8 stop the treat dispensing by breaking out of the loop.
However, only the inner for
loop is exited. The outer loop still keeps iterating with all the dogs, and therefore it prints something even after the treats run out due to the print statements on lines 5 and 11.
To fix this code, another break
statement is needed in the outer loop.
Example:
dogs = ["Scooby-Doo", "Snoopy", "Goofy", "Clifford", "Astro"] num_of_treats = 10 for dog in dogs: if num_of_treats == 0: break print(f"{dog} gets treat", end="") for i in range(3): if num_of_treats == 0: break print(f" #{i+1}", end="") num_of_treats -= 1 print(". Woof!")
Output:
Scooby-Doo gets treat #1 #2 #3. Woof! Snoopy gets treat #1 #2 #3. Woof! Goofy gets treat #1 #2 #3. Woof! Clifford gets treat #1. Woof!
In the above code, and additional if
and break
statement combination was placed on lines 5 and 6 to fix the problem.
Summary & Reference for the Python break Statement
The Python break
statement provides a way to prematurely exit loops before their natural completion.
To use the break
statement, simply write break
on its own line within a loop. It is commonly used within conditional statements like if
to check for a specific condition and exit the loop accordingly.
In for
loops, the break
statement proves useful when there is an additional condition other than reaching the last item that necessitates ending the loop.
for dog in dogs: if num_of_treats == 0: break # Code for giving treats
In while
loops, the break
statement is especially useful when the loop stopping condition is not known at the beginning of the iteration.
while True: # Code for getting user input if user_input.lower() == 'exit': break # Code for processing user input
When used within nested loops, the break
statement affects only the innermost loop where it is located.