Skip to main content

Python break Statement

break Statement

Python's break instruction is used to immediately exit the loop that contains it.

note

In contrast to the continue statement, the loop does not continue with the next iteration, but ends.

Break in for and while Loop

The break statement is used to exit the loop immediately. It simply jumps out of the while loop and the program continues to execute the code after the loop.

For example, break the loop at yellow:

For Loop
colors = ['red', 'green', 'yellow', 'blue']
for x in colors:
if x == 'yellow':
break
print(x)

Output

red
green
While Loop
colors = ['red', 'green', 'yellow', 'blue']
i = 0
while i < len(colors):
i = i + 1
if colors[i-1] == 'yellow':
break
print(colors[i-1])

Output

red
green

Break and else clause in for and while Loop

If the loop ends prematurely with break, the else clause will not be executed.

For example, break the loop at yellow and see that the else clause is not executed:

For Loop
colors = ['red', 'green', 'yellow', 'blue']
for x in colors:
if x == 'yellow':
break
print(x)
else:
print('Done!')

Output

red
green

Now, change the colors array and observes how the else clause is executed:

For Loop
colors = ['red', 'green', 'yellow', 'blue']
for x in colors:
if x == 'light blue':
break
print(x)
else:
print('Done!')

Output

red
green
yellow
blue
Done!
note

This behaviour applies to both for and while loops!

Break inside try…finally Block

If you have a try-finally block within a for or while statement, after the break statement is executed, the finally clause is executed before exiting the loop.

For example, a try…finally block in a for loop:

For Loop
for x in range(5):
try:
print('trying...')
break
print('still trying...')
except:
print('Something went wrong.')
finally:
print('Done!')

Output

trying...
Done!

For example, a try…finally block in a for loop:

While Loop
while 1:
try:
print('trying...')
break
print('still trying...')
except:
print('Something went wrong.')
finally:
print('Done!')

Output

trying...
Done!