Break Keyword In Python

Overview:

  • The break statement in Python can be provided inside a, for loop or while loop.

 

  • break is a keyword in Python.

 

  • Unlike other programming languages like C++ and Java, Python does not have a switch statement. So, no switch, case blocks.

 

  • The break statement in Python makes the execution to immediately leave to the next enclosing block.

 

  • In case break is encountered in a for/while which is inside a try block with a finally clause, the finally will be executed before the break comes into affect.

The break statement - keyword in Python

Fig: Break Statement in Python

Example:

#Sample Python program that generates Fibonacci numbers

def genFibo(fiboCount):

        firstTerm   = 0

        secondTerm  = 1

        nextTerm    = 0

 

        count       = 0

        for i in range(0,20):

            if ( i <= 1 ):

                nextTerm = i

 

            else:

                nextTerm    = firstTerm + secondTerm

                firstTerm   = secondTerm

                secondTerm  = nextTerm

 

            print(nextTerm)

            count = count+1

 

            if count is fiboCount:

                print("%d numbers generated in fibonacci series..coming out of the loop"%(fiboCount))

                break

 

fiboCount = 5

genFibo(fiboCount)

 

Output:

0

1

1

2

3

5 numbers generated in fibonacci series..coming out of the loop

 

 


Copyright 2023 © pythontic.com