Python break Statement

Python 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.

If the 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.

Python 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")

Program output.

p
y
t
Statement after loop body

Flowchart of break Statement

The flowchart of the break statement in a Python loop.

Python break statement flowcart
Python break statement flowcart

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");  

Program output.

1
2
3
4
The Loop Ends

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.