Python Break Statement

In python, break statement is useful to stop or terminate the execution of loops such as for, and while before the iteration of sequence items completed.

 

If you use a break statement inside the nested loop, it will terminate the inner loop's execution.

Break Statement Syntax

Following is the syntax of defining the break statement in python.

 

break

Break Statement Flow Chart

Following is the flow chart diagram of the break statement in python.

 

Python break statement flow chart diagram

 

If you observe the above break statement flow chart diagram, the execution of conditional block statements will be stopped when the break statement is executed.

Python Break Statement in For Loop

In python, you can use break statement in for loop to stop or terminate the execution of the current loop, and the program execution will move immediately to the statements after the body of the loop.

 

Following is the example of using a break statement in python for loop to stop the loop's execution based on the defined condition.

 

for x in range(5):

  if x == 3:

    break

  print(x)

print("Loop Exection Finished")

When you execute the above python program, you will get the result like as shown below.

 

0

1

2

Loop Exection Finished

If you observe the above result, the for loop terminated without looping through all the items and executed the statements immediately after the body of the loop.

Python Break Statement in While Loop

Like python for loop, you can also use break statement in a while loop to terminate the loop's execution based on your requirements.

 

Following is the example of using a break statement in python while loop to stop the loop's execution based on the defined condition.

 

a = 1

while a < 5:

  if a == 3:

    break

  print(a)

  a += 1

print("Outside of Loop")

When you execute the above python program, you will get the result like as shown below.

 

1

2

Outside of Loop

If you observe the above result, the while loop terminated without looping through all the items and executed the statements outside of the loop.

 

This is how you can use break statement in python for and while loops to terminate the loops' execution based on your requirements.