Break Statement

Overview:

The break statement in python can appear inside a for or while loop.

When a break statement is executed it terminates the immediate enclosing 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.

Example1:

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

 

Example2:

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 function1(15)will make the break statement to be executed. However, python makes sure that the finally block is executed before the loop exit.


Copyright 2019 © pythontic.com