Curriculum
In this lesson, you will learn about the break statement in python with its syntax and also how to use it in for loop and while loop of your python program.
When you have to override a loop or you need to exit the loop or even omit an iteration based on an external condition, you use loop control statements.
Loop control statements exist in the loop when a certain external condition is met it jumps out of the loop and it executes the immediate next line of code after the loop. Loop control statements change execution from its normal sequence.
Python supports the following loop control statements:
The break statement in Python terminates the current loop and alters the program flow when a certain condition is met or an external condition is triggered and executes the next immediate statement. Its working is similar to break statements in other programming languages like C and Java. It can be used for both while and for loops.
Now let’s say, the break statement is affixed in a nested loop, in that case, the break statement will terminate the innermost loop.
Syntax:
break
Sample program using break statement in while loop
Input
a = 57 while a: print(a) a=a+1 if a == 65: break print("came out of while loop")
Output
57 58 59 60 61 62 63 64 came out of while loop
Sample program using break statement in for loop
Input
for str in "Developer Publish Academy": if str == "i": break print(str) print("The end")
Output:
D e v e l o p e r P u b l The end