break Statement
Python's break instruction is used to immediately exit the loop that contains it.
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:
colors = ['red', 'green', 'yellow', 'blue']
for x in colors:
if x == 'yellow':
break
print(x)Output
red
greencolors = ['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
greenBreak 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:
colors = ['red', 'green', 'yellow', 'blue']
for x in colors:
if x == 'yellow':
break
print(x)
else:
print('Done!')Output
red
greenNow, change the colors array and observes how the else clause is executed:
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!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 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 1:
try:
print('trying...')
break
print('still trying...')
except:
print('Something went wrong.')
finally:
print('Done!')Output
trying...
Done!