break statement

Break Statement in Python


The break statement terminates the loop containing it. Control of the program flows to the statement immediately after the body of the loop.

A while or for loop will iterate till the condition is tested false, but one can even transfer the control out of the loop (terminate) with help of break statement. When the break statement is executed, the control flow of the program comes out of the loop and starts executing the segment of code after the loop structure.

If break statement is inside a nested loop (loop inside another loop), break will terminate the innermost loop.

Syntax:

break

The working of break statement in for loop and while loop is shown below.

Example : Program to illustrate the use of break statement inside for loop

for word in “Jump Statement”:
if word = = “e”:
break
print (word, end= ' ')

Output:

Jump Stat


Example : Program to illustrate the use of break statement inside for loop

for word in “Jump Statement”:
if word = = “e”:
break
print (word, end=”)
else:
print (“End of the loop”)
print (“\n End of the program”)

Output:

Jump Stat

End of the program

Note that the break statement has even skipped the ‘else’ part of the loop and has transferred the control to the next line following the loop block.