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
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
for x in range(1, 10): print(x) if x == 4: break
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
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)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.