Python break Statement

Python break statement is used to exit the loop immediately. It simply jumps out of the loop altogether, and the program continues after the loop.

Break in for and while Loop

Here’s how you can implement break in a for and while loop.

# Break the for loop at 'blue'
colors = ['red', 'green', 'blue', 'yellow']
for x in colors:
    if x == 'blue':
        break
    print(x)
# Prints red green
# Break the while loop when x becomes 3
x = 6
while x:
    print(x)
    x -= 1
    if x == 3:
        break
# Prints 6 5 4

The Else Clause

If the loop terminates prematurely with break, the else clause won’t be executed.

# Break the for loop at 'blue'
colors = ['red', 'green', 'blue', 'yellow']
for x in colors:
    if x == 'blue':
        break
    print(x)
else:
    print('Done!')
# Prints red green
# Break the while loop when x becomes 3
x = 6
while x:
    print(x)
    x -= 1
    if x == 3:
        break
else:
    print('Done!')
# Prints 6 5 4

Break Inside try…finally Block

If you have try-finally block inside a for or while statement; after execution of break statement, the finally clause is executed before leaving the loop.

# in a for statement
for x in range(5):
  try:
      print('trying...')
      break
      print('still trying...')
  except:
      print('Something went wrong.')
  finally:
      print('Done!')
# Prints trying...
# Prints Done!
# in a while statement
while 1:
  try:
      print('trying...')
      break
      print('still trying...')
  except:
      print('Something went wrong.')
  finally:
      print('Done!')
# Prints trying...
# Prints Done!