what is use of 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.

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

number = 0

for number in range(10):
    if number == 5:
        break    # break here

    print('Number is ' + str(number))

print('Out of loop')

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.

Within the  for loop, 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.

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.

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

When we run this code, our output will be the following:

OutputNumber is 0
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.

Was this article helpful?
YesNo

Leave a Comment