Loop with else clause
__peter__ at web.de
Tue Feb 5 03:43:54 EST 2019
DL Neil wrote:
> What is the pythonic way to handle the situation where if a condition
> exists the loop should be executed, but if it does not something else
> should be done?
> Possible solution:
> To make anything more than the trivial case readable, I think I'd put
> the list processing into one function, and the exception into another
> (except that this case is so trivial), ie
> if list:
> process_list() #the heading and for-loop, as above
> print( "Sorry...
> Others wanted to add a semaphore/flag inside the loop to indicate if it
> was executed at least once. Yes, could even use the else clause then!
An argument in favour of the flag is that it works with arbitrary iterables
whereas if ...: fails:
>>> numbered = enumerate()
>>> if numbered:
... print("the winners are")
... for ix in numbered: print(*ix)
the winners are
> The ideas went (rapidly) down-hill from there...
> Is there another, more pythonic, approach to conditional (for/while)
> loop processing?
I'm not aware of such an approach.
More information about the Python-list