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

Loop with else clause

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 it! 
The coder intended to implement the scenario (above) but did not realise 
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 are 
mutually-exclusive*) - which one assumes is the reason why the BDfL is 
claimed to have said it should never have been implemented (this way). 
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 really 
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 fulfilled 
the requirements of a competition from which a winner will be randomly 

The names all appear in a list, so the most frequent use-case is trivial:

	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 it 
was executed at least once. Yes, could even use the else clause then!

The ideas went (rapidly) down-hill from there...

Is there another, more pythonic, approach to conditional (for/while) 
loop processing?