Python course menu
Python break Statement: Exit a Loop Early
Learn the Python break statement: stop a for or while loop as soon as you find what you need, break in nested loops, break with for-else, and when to use return instead.
On this page
Sometimes there is no point finishing a loop: you were searching for something and found it, or an error means the rest of the work is pointless. break stops the loop immediately and continues with the first line after it.
break in a for loop#
Find the first number over 10:
numbers = [4, 9, 15, 22, 7]
for n in numbers:
if n > 10:
print("First number over 10:", n)
break
print("checked", n)checked 4
checked 9
First number over 10: 1522 and 7 are never checked. On a list of a million items, stopping early can save a lot of work.
break in a while loop#
break is the usual way out of a while True loop:
total = 0
while True:
value = int(input("Number (-1 to stop): "))
if value == -1:
break
total += value
print("Total:", total)See while Loops in Depth for the full example.
break with for-else#
A loop's else block runs only if the loop finished without a break. Together they express "search, and do something if nothing was found":
emails = ["a@x.com", "bad-email", "c@x.com"]
for e in emails:
if "@" not in e:
print("Invalid email found:", e)
break
else:
print("All emails valid")Invalid email found: bad-emailIf every email contained @, the loop would end normally and All emails valid would be printed.
break only exits one loop#
In nested loops, break leaves only the innermost loop:
for i in range(3):
for j in range(3):
if j == 1:
break
print(i, j)0 0
1 0
2 0The inner loop stops at j == 1 each time, but the outer loop carries on.
To leave several loops at once, the cleanest options are to put the loops in a function and return, or to set a flag variable and check it in the outer loop.
return instead of break#
Inside a function, return both exits the loop and hands back the answer:
def find_index(items, target):
for i, item in enumerate(items):
if item == target:
return i
return -1
print(find_index(["a", "b", "c"], "b"), find_index(["a"], "z"))1 -1Common mistakes#
Practice#
Practice exercise
Starting from 2, find the first number that is divisible by both 7 and 2, print it, and stop.
Show hint
Loop over range(2, 30), test n % 7 == 0 and n % 2 == 0, and break when true.
Show solution
for n in range(2, 30):
if n % 7 == 0 and n % 2 == 0:
print(n)
break14Without break, the loop would also print 28.
Key takeaway#
Finished this lesson?