import itertools
# Break with itertools.count (infinite iterator)for i in itertools.count(1):
if i * i > 100:
print(f"First square > 100: {i}^2 = {i*i}")
break# Using break to implement takewhile manuallydeftake_until(predicate, iterable):
result = []
for item in iterable:
if predicate(item):
break
result.append(item)
return result
data = [2, 4, 6, 7, 8, 10]
evens = take_until(lambda x: x % 2 != 0, data)
print(f"Evens before first odd: {evens}")
# Break with walrus operator
nums = iter([3, 1, 4, 1, 5, 0, 2, 6])
while (n := next(nums, None)) isnotNone:
if n == 0:
print("Hit zero, stopping")
breakprint(n, end=" ")
print()
Output
Click "Run" to execute your code
break works with any loop, including those over infinite iterators. Combined with walrus operator, it enables clean sentinel-based loops.
Challenge
Try modifying the code above to explore different behaviors. Can you extend the example to handle a new use case?