Python For Break is used to stop the loop before it has looped through all the items. For that, you have to use the if statement to match the break loop condition.
It is commonly used within loops such as for
and while
to interrupt the execution and immediately exit the loop.
Python for break example
Simple example code exit for a loop if the value is “apple“.
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "apple":
print("Break Loop")
break
Output:
Another Example
for x in range(1, 10):
print(x)
if x == 4:
break
Output:
1
2
3
4
Similarly, you can use break
within a while
loop. Here’s an example:
count = 0
while count < 5:
if count == 3:
break
print(count)
count += 1
print("Loop finished.")
In this case, the loop continues to execute until the condition count < 5
becomes False
. However, when count
reaches the value 3
, the break
statement is encountered, causing the loop to terminate immediately.
That’s how you can use the break
statement in Python to prematurely exit a loop based on a specific condition.
Comment if you have any doubts or suggestions on this Python break keyword.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.