You are reading solutions / Python

# Python break statement: break for loops and while loops

Python's break statement allows you to exit the nearest enclosing while or for loop. Often you'll break out of a loop based on a particular condition, like in the following example:

s = 'Hello, World!'

for char in s:
print(char)
if char == ',':
break
Out:
H
e
l
l
o
,

if, while and for statements are fundamental in any large Python script (and in a few small ones). These statements follow a stringent set of rules predefined by Python, so we sometimes need to use what are known as control statements to influence them. The three control statements are pass, continue and break, allowing you to govern your code in different manners.

In this article, we'll look specifically at the break statement.

## Example 1: Break while loops

As mentioned in the introduction, break terminates its enclosing loop. Usually, a break statement is linked to a specific condition, only triggering break after meeting predefined requirements.

In the following example, we'll find the first ten multiples of seven by using the modulo operator (%) and a break command:

number = 0
multiple_list = []

while True:
number += 1
if number % 7 == 0: # % 7 returns zero for numbers which are multiples of 7
multiple_list.append(number)

if len(multiple_list) == 10:
# ten multiples have been found, exit the loop
break

multiple_list
Out:
[7, 14, 21, 28, 35, 42, 49, 56, 63, 70]

Using a while loop enables Python to keep running through our code, adding one to number each time. Whenever we find a multiple, it gets appended to multiple_list. The second if statement then checks to see if we've hit ten multiples, using break to exit the loop when this condition is satisfied. The flowchart below shows the process that Python is following in our example:

## Example 2: Break nested loops

break will terminate the nearest encompassing loop, but this can get a little confusing when working with nested loops. It's important to remember that break only ends the inner-most loop when used in a script with multiple active loops.

Let's consider the following example:

strings = ['This ', 'is ', 'a ', 'list ']

# iterate through each string in the list
for string in strings:

# iterate through each character in the string
for char in string:
print(char)

if char == 'i':
# if the character is equal to 'i', terminate the nested for loop
print('break\n')
break
Out:
T
h
i
break

i
break

a

l
i
break

For any strings that contain an i, break exits our for char in string: loop. As this is our inner-most loop, Python then moves onto the next item in the for string in strings: loop.

## Example 3: Break infinite Loops

It's worth noting that if Python doesn't terminate while loops, they can loop endlessly. Therefore, when relying on a break statement to end a while loop, you must ensure Python will execute your break command.

Let's consider our previous example, where we wrote a script to find the first ten multiples of seven:

# This is an infinite loop. Can you see why?
while True:
res = input("Enter the number 5: ")
if res == 5:
break
Out:
Enter the number 5:  5
Enter the number 5:  5
Enter the number 5:  5

The above code is a common example of handling user input for menu selections in a terminal. The problem with this example is that res will never equal 5 (integer-type) because input(...) returns '5' (string-type). The break statement is never reached. The correct way to handle this scenario is to cast res to an int, like so:

# This is an infinite loop. Can you see why?
while True:
res = input("Enter the number 5: ")
try:
res = int(res)
except:
pass

if res == 5:
print("Thanks!")
break
Out:
Enter the number 5:  2
Enter the number 5:  5
Out:
Thanks!

It can be hard to spot when one of your background processes gets caught in an infinite loop. You're not breaking any of Python's rules by getting stuck in a loop, so there are often not any helpful error messages to let you know what you've done wrong.

Minor typos like in the example above can also be very hard to spot when you're debugging. As a result, a great rule of thumb to follow is always to double-check your break conditions as you're writing them.

## Summary

break is an excellent way of controlling your scripts, hence why it's called a control statement. It terminates whichever loop it's placed within, causing Python to resume whatever line of code comes after the loop. For situations that make use of nested loops, break will only terminate the inner-most loop. Just make sure you always double-check that your break statements will get activated when you want them to.