Loop with else clause
I don't know if it is very Pythonic, but I would do something like
print ("Sorry ...")
And yes, that for/else construct can be confusing.
>>> On 5-2-2019 at 5:29, DL Neil <PythonList at DancesWithMice.info>
> 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?
> Why am I asking?
> Today's code review included a for...else structure. I've rarely seen
> such a thing, and even knowing it exists, cannot recall ever using
> The coder intended to implement the scenario (above) but did not
> that the else-clause means 'execute if the loop ended without using
> break'. She thought it meant 'if there's nothing in the iterable,
> execute the else clause' (per if...then...else... ie the two clauses
> mutually-exclusive*) - which one assumes is the reason why the BDfL
> claimed to have said it should never have been implemented (this
> She neglected to test the exception properly, and was lulled into a
> false sense of security by the coverage reporting 100%. Oops!
> *see also the more commonly-used try...except...else...[finally...]
> When/how does this occur?
> Our client is more than a little commercially-sensitive. So as a
> simple scenario, imagine a report is required, naming people who have
> become eligible for something, eg students qualified to enter an
> advanced class, Oscar film award nominees, entrants who have
> the requirements of a competition from which a winner will be
> The names all appear in a list, so the most frequent use-case is
> print( "And the winners are:" )
> for name in list:
> print( name )
> but, if no-one actually qualifies, a warning message is required, eg
> print( "Sorry, no-one is eligible" )
> 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
> was executed at least once. Yes, could even use the else clause
> The ideas went (rapidly) down-hill from there...
> Is there another, more pythonic, approach to conditional (for/while)
> loop processing?