Break statement in Python

In Python, the break statement provides you with the opportunity to exit out of a loop when an external condition is triggered. You’ll put the break statement within the block of code under your loop statement, usually after a conditional if statement.

Flowchart of break statement :


Let’s look at an example that uses the break statement in a for loop:






number = 0
for number in range(10):
   number = number + 1
   if number == 5:
      break # break here
   print('Number is ' + str(number))
print('Out of loop')



Explanation:

1

In this small program, the variable number is initialized at 0. Then a for statement constructs the loop as long as the variable number is less than 10.

2

Within the for loop, the number increases incrementally by 1 with each pass because of the line number = number + 1.

3

Then, there is an if statement that presents the condition that if the variable number is equivalent to the integer 5, then the loop will break.

4

Within the loop is also a print() statement that will execute with each iteration of the for loop until the loop breaks, since it is after the break statement.

5

To see when we are out of the loop, we have included a final print() statement outside of the for loop.

output of above example  :






Number is 1

Number is 2

Number is 3

Number is 4

Out of loop



This shows that once the integer number is evaluated as equivalent to 5, the loop breaks, as the program is told to do so with the break statement.

The break statement causes a program to break out of a loop.


advertisement