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.

Example: Break the loop at ‘blue’

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

Output:

red green

Example: Break the loop when x becomes 3

x = 6
while x:
    print(x)
    x -= 1
    if x == 3:
        break

Output:

6 5 4

The Else Clause

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

Example: Break the loop at ‘blue’

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

Output:

red green

Example: Break the loop when x becomes 3

x = 6
while x:
    print(x)
    x -= 1
    if x == 3:
        break
else:
    print('Done!')

Output:

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.

Example: A for statement

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

Output:

trying...
Done!

Example: A while statement

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

Output:

trying...
Done!