What is the use of break and continue in Python?
In Python, break and continue statements can alter the flow of a normal loop. Loops iterate over a block of code until the test expression is false, but sometimes we wish to terminate the current iteration or even the whole loop without checking test expression.
The break and continue statements are used in these cases.
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
Syntax of break
Let’s look at an example that uses the
break statement in a
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.
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
To know when we are out of the loop, we have included a final
print() statement outside of the
When we run this code, our output will be the following:
Number is 0
Number is 1
Number is 2
Number is 3
Number is 4
Out of loop