Break Statement

Overview:

The break statement is an early exit mechanism from the iterative loops like for and whilebreak 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

def f1():

    break

   

f1()

 

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.

Example 1:

def BreakTest():

    Basket = ["Apple", "Orange", "Banana", "drygrass", "brinjal", "potato"]

   

    # print only baskets

    for item in Basket:

        if item == "drygrass":

            break

 

        print(item)

 

    print("Processed all the fruits")

 

BreakTest()

Output:

Apple

Orange

Banana

Processed all the fruits

 

Example 2:

def function1(RangeInput):

    try:

        for x in range(0,RangeInput):

            if(x > 10):

                print("Executing Break")

                break

               

            print(x)

    except:

        print("Inside except")

    finally:

        print("Inside finally")       

       

function1(5)

function1(15)   

 

Output:

0

1

2

3

4

Inside finally

0

1

2

3

4

5

6

7

8

9

10

Executing Break

Inside finally

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.


Copyright 2023 © pythontic.com