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.
Fig: Break Statement in Python
#Sample Python program that generates Fibonacci numbers
firstTerm = 0
secondTerm = 1
nextTerm = 0
count = 0
for i in range(0,20):
if ( i <= 1 ):
nextTerm = i
nextTerm = firstTerm + secondTerm
firstTerm = secondTerm
secondTerm = nextTerm
count = count+1
if count is fiboCount:
print("%d numbers generated in fibonacci series..coming out of the loop"%(fiboCount))
fiboCount = 5
5 numbers generated in fibonacci series..coming out of the loop