Python break Statement

  • The break statement in Python is used to get out of the current loop.
  • We can’t use break statement outside the loop, it will throw an error as “SyntaxError: ‘break’ outside loop“.
  • We can use break statement with for loop and while loops.
  • If the break statement is present in a nested loop, it terminates the inner loop.
  • The “break” is a reserved keyword in Python.

Flow Diagram of break Statement

Break Statement Flow Diagram
Break Statement Flow Diagram

Python break Statement Syntax

The break statement syntax is:

break

We can’t use any option, label or condition with the break statement.


Python break Statement Examples

Let’s look at some examples of using break statement in Python.

1. break statement with for loop

Let’s say we have a sequence of integers. We have to process the sequence elements one by one. If we encounter “3” then the processing must stop. We can use for loop for iteration and break statement with if condition to implement this.

t_ints = (1, 2, 3, 4, 5)

for i in t_ints:
    if i == 3:
        break
    print(f'Processing {i}')

print("Done")

Output:

Python Break Statement For Loop
Python break Statement with for Loop

2. break statement with the while loop

count = 10

while count > 0:
    print(count)
    if count == 5:
        break
    count -= 1

Output:

Python Break Statement While Loop
Python break Statement with while Loop

3. break statement with a nested loop

Here is an example of break statement within the nested loop.

list_of_tuples = [(1, 2), (3, 4), (5, 6)]

for t in list_of_tuples:
    for i in t:
        if i == 3:
            break
        print(f'Processing {i}')

Output:

Python Break Statement Nested Loop
Python break Statement Nested Loop

Why Python doesn’t support labeled break statement?

Many popular programming languages support a labelled break statement. It’s mostly used to break out of the outer loop in case of nested loops. However, Python doesn’t support labeled break statement.

PEP 3136 was raised to add label support to break statement. But, it was rejected because it will add unnecessary complexity to the language. There is a better alternative available for this scenario – move the code to a function and add the return statement.