How to break out of multiple loops in Python?
In this tutorial, we will learn how to break out of multiple loops in Python with some cool and easy examples.
I know, you have faced so many problems in Python to break out from multiple loops. Python Language has so many inbuilt functions so that you can ease your work.
Break statement in Python
To terminate the continuous running loop we use the break statement.
NOTE:- If there is nested looping, the break statement will work for an innermost loop.
Below is the syntax for the break statement:
break
Exapmle 1:
See the Python code below:
for i in range (0,10): if i == 5: break print(i) print("stop")
Output: 0 1 2 3 4 stop
Example 2:
There is a certain machine that will count the number of platelets in the Human Body. If the platelets are lower then 65000, it will tell doctor to consult that patient first and there will be 1000 platelets degrading per hour.
platelets = 150000 while platelets > 0: print("platelets count of patient is",platelets) platelets = platelets - 10000 if platelets < 95000: break print("Doctor consult this patient first")
Output: platelets count of patient is 150000 platelets count of patient is 140000 platelets count of patient is 130000 platelets count of patient is 120000 platelets count of patient is 110000 platelets count of patient is 100000 Doctor consult this patient first
In this article, we learned about the break statement in python and how to terminate an infinite loop or any nested or simple loop. If you have any queries please comment below.
Also, read: Break and Continue Statement in Python
Leave a Reply