Skip to content

Python break Statement

How to use Python's break statement to immediately exit loops in for and while constructs, including its interaction with else clauses and try-finally blocks.

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:

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

Output

red
green
While Looppython
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 Looppython
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 Looppython
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 Looppython
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 Looppython
while 1:
  try:
      print('trying...')
      break
      print('still trying...')
  except:
      print('Something went wrong.')
  finally:
      print('Done!')

Output

trying...
Done!
Navigation