break statement is used to terminate the a loop which contains the
break statement. When a
break statement is executed inside a loop, the program execution jumps to immidiately next statement after the loop.
break statement is inside a nested loop (one loop inside another loop), the
break statement will terminate the enclosing loop which contains the break statement.
break Statement Example
Gives is a Python program which iterates over the characters of sequence “Python”. The loop uses
break statement to terminate immidiately as soon as character ‘h’ is encounterd in conditional expression of if statement.
for s in "python": if s == "h": break print(s) print("Statement after loop body")
p y t Statement after loop body
The flowchart of the break statement in a Python loop.
Python break statement with while loop
Python example to showcase the use of breat statement with the while loop.
The program prints the number, sequentially, starting with 1. It prints the number till 4. The condition
i == 5 becomes True, and the loop exits.
i = 1; while True: print(i), i=i+1; if i == 5: break; print("The Loop Ends");
1 2 3 4 The Loop Ends
Happy Learning !!