In Python, you can use the break
statement to exit a loop prematurely when a specific condition is met. It is commonly used in while
or for
loops. Here’s how you can use break conditions in different scenarios:
1. Using break
in a while
loop:
i = 0
while True:
print(i)
i += 1
if i == 5: # Break condition
break
Explanation: This loop runs indefinitely (while True
) but breaks when i
reaches 5.
2. Using break
in a for
loop:
for i in range(5):
if i == 3: # Break condition
break
print(i)
Explanation: This loop iterates through numbers from 0 to 4 but stops (breaks) when i
equals 3.
3. Using break
with an if
condition:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for num in numbers:
if num > 5: # Break condition
break
print(num)
Explanation: The loop prints numbers until it encounters a number greater than 5, then exits the loop.