else clauses in while and for loops

Jonathan Giddy jon at dgs.monash.edu.au
Fri Apr 14 19:51:43 EDT 2000


Chuck Esterbrook declared:
>
>So did anyone present, in this thread, an example that shows a real need?

The difficulty is what will you accept as a "real need"?  It sounds like you 
want an example that cannot be done any other way.  Even those who like else 
clauses in for and while will admit they're not essential.

Just like there's no "real need" for tuples (use lists), for loops (use
while), or elif (use else: if). 

All of these concepts are redundant in the sense that they can be mimicked
using an alternative sequence of code.  But they're nice because they
express higher-level concepts about the algorithm.

OTOH, a quick look at my code shows that I regularly use tuples, for
loops, and elif, but I rarely use else with anything but if and
try..except clauses.

The only example I found creates a list of usable temporary directories on
Unix, checking the environment first.  Certainly no real need here.

_tmpdirs = ['/tmp', '/var/tmp']

for envname in ['TMPDIR', 'TMP', 'TEMP']:
    try:
	paths = [os.environ[envname]]
    except KeyError:
	pass
    else:
	basepaths = validate_paths(paths)
	if basepaths:
	    break
else:
    basepaths = validate_paths(_tmpdirs)







More information about the Python-list mailing list