Last modified: Jan 10, 2023 By Alexander Williams
How to Break out a loop in Python
Probably you want to break out your python loop after the statement is true.
So in this article, we'll learn how to break out a loop in python.
Breaking out a for loop
Example 1
""" print all the languages list items before 'Python' """
#list
languages = ["Ruby", "Javascript", "Php", "Python", "Go" ]
for i in languages:
print(i)
if i == "Python":
break
output
Ruby
Javascript
Php
Python
in the above example, the loop has broken when did it reach to "Python" item
Example 2
""" this code is counting and break when it reaches in 50 """
x = 50
for i in range(100):
print(i)
if i == x:
break
output
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
.
.
.
.
.
50
as you can see in this second example, tho loop has broken when it reaches 50
Breaking out a while loop
Example 1
""" the loop will break when it reaches 10 """
x = 1
while x < 50:
print(x)
if x == 10:
break
x += 1
output
0
1
2
3
4
5
6
7
8
9
10
as you can see the while loop has broken when it reaches 10.
Conclusion
in this article, we've learned how to use break in for and while loop.
if you want to know when you should use for and while loop, recommended visiting for vs wihle loop in python