Check whether break condition was triggered
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Magic Ocean Looping
--
Chapters
00:00 Question
01:11 Accepted answer (Score 4)
01:27 Answer 2 (Score 1)
02:48 Thank you
--
Full question
https://stackoverflow.com/questions/4778...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #loops #break #sentinel
#avk47
ACCEPTED ANSWER
Score 5
Use for/else. That's specifically what it's for.
for k in range(n):
if condition:
print("Broke at", k)
break
else:
print("Never broke")
ANSWER 2
Score 1
Not necessarily better, but often you can condense the loop into a use of any or all (for when you only care if a value was found) or next (for when you care about the value found).
For example, to find the first item satisfying some test, or None if no such item exists, you can use two-arg next plus a generator expression:
needle = next((x for x in haystack if isneedle(x)), None)
if needle is not None:
... do stuff with needle ...
else:
... no needle ...
or roughly equivalently with one-arg next and exception handling:
try:
needle = next(x for x in haystack if isneedle(x))
except StopIteration:
... no needle ...
else:
... do stuff with needle ...
A realistic use case might be identifying a prime number via trial division. In that case, you don't care what factor you found, you just care that there was a factor, so you could write a testing function as:
num = ...
isnumprime = num >= 2 and all(num % f != 0 for f in range(2, int(num ** 0.5) + 1))
for/else is a perfectly adequate way to do this (see other answers), but any/all/next (usually with generator expressions) can be cleaner in specific contexts.