Python Break Statement

The break statement in Python is used to exit a loop prematurely. It is commonly used inside for and while loops when a specific condition is met, terminating the loop and continuing execution with the next statement after the loop.

What is the Break Statement?

The break statement is used to stop the execution of a loop before it has gone through all iterations. It is useful when you want to exit a loop once a specific condition has been met.

Syntax of Break Statement

Syntax


while condition:
if some_condition:
    break
# Code block to execute
        

Explanation:

In this syntax:

Example: Break the loop when counter reaches 3

          
counter = 1
while counter <= 5:
if counter == 3:
    break
print(counter)
counter += 1
        

Output

1 2

In this example, the while loop runs as long as counter <= 5. When counter reaches 3, the break statement is executed, causing the loop to terminate. The output shows the numbers 1 and 2, and the loop stops without printing 3 or higher values.

Example: Break the loop when counter reaches 3


for i in range(1, 6):
if i == 4:
    break
print(i)
        

Output

1 2 3

In this example, the for loop iterates over the numbers from 1 to 5. When i == 4, the break statement is executed, stopping the loop prematurely. The output shows the numbers 1, 2, and 3 before the loop is broken.

Best Practices for Using Break