The break statement in python is used to terminate the execution of the nearest enclosing loop in which it appears. The break statement is widely used with for loop and while loop. When compiler encounters a break statement, the control passes to the statement that follows the loop in which break statement appears. It’s syntax is quite simple, just type keyword break as shown below.
Let’s write a program to demonstrate the break statement
i = 1 while i <= 10: print(i, end=" ") if i == 5: break i = i + 1 print("\n Done")
#output 1 2 3 4 5 Done
Note that the code is meant to print the first 10 numbers using a while loop, but it will actually print only numbers from 1 to 5. As soon as i becomes equal to 5, the break statement is executed and the control jumps to the statement following the while loop.
Hence the break statement is used to exit a loop from any point within its body by passing its normal termination expression. When the break statement is encountered inside a loop, the loop is immediately terminated and program control is passed to the next statement following the loop.
The following syntax shows the transfer of control when break statement is encountered.
while ...: ... if condition: break ... ... Transfers control out of the while loop
for ...: ... if condition: break ... ... Transfers control out of the for loop
for ...: ... for ...: if condition: break ... ... Transfers control out of inner for loop