The break statement is an early exit mechanism from the iterative loops like for and while. break is one of the keywords in Python.
A break statement in Python can appear inside a for or while loop.
When a break statement is executed it terminates the immediate enclosing loop. The control is transferred to the next statement following the loop.
Similar to continue, the break statement as well cannot appear without a scope of a for or while construct.
#break can not be used like this
The break statement cannot be used as above. Python will report an error stating “SyntaxError: 'break' outside loop”, if the break statement is used as given in the above python snippet.
When the break statement is executed inside a try block, Python will execute the finally block before the control is transferred out of the loop.
Basket = ["Apple", "Orange", "Banana", "drygrass", "brinjal", "potato"]
# print only baskets
for item in Basket:
if item == "drygrass":
print("Processed all the fruits")
Processed all the fruits
for x in range(0,RangeInput):
if(x > 10):
In the above example, the call to function1(15)will make the break statement to be executed. However, Python makes sure that the finally block is executed before the loop exits.