[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Loop with else clause

As mentioned somewhere, "readability counts", so why not just go with exactly what you said...

if len(nominees) > 0:                #if a condition exists
    for nominee in nominees:         #the loop should be executed
else:                                #but if not
    print("D'oh! No one is worthy.") #something else should be done

The fancy features of the language can be cool and all, but forcing yourself to use them just for the sake of using them and "being pythonic" can result in weird situations, and wrong or unclear assumptions or intents. When someone else reads it later it may hide what you were actually intending the check to look for.

Hmm, "if nominees:" Did they make it like that to look for a 0 length list, or to make sure they didn't get None by accident, or both, or something different?

Hmm, "if len(nominees) > 0:" Ahh ok, we want to make sure there's something in there.

So my 2 cents: Feel free to be non-pythonic if it makes things clear and works.

-----Original Message-----
From: Python-list [ at] On Behalf Of Peter Otten
Sent: Tuesday, February 05, 2019 3:44 AM
To: python-list at
Subject: Re: Loop with else clause

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
> else:
>     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.