else clauses in while and for loops

Chuck Esterbrook echuck at mindspring.com
Fri Apr 14 20:09:52 EDT 2000


Jonathan Giddy wrote:

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

I don't know why you think it 'sounds like' that. Most of the posts didn't have any examples and the one that did wasn't all that cogent. I'm just looking for something that is [a] an example and [b] shows some obvious advantage.


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

I'm aware of all of this. In fact, I think we could all get our work done with ADD, NEG, JMP and JMPZ.   :-)

But no thank you.



> 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)

This example looks good to me. It eliminates a redundant "if" after the "for" loop to see if "basepaths" still needs to be set.

Thanks.


On another topic: With regards to the "try...except" technique above (which I've seen quite a bit in Python) does the following code do the same thing and if so, which do you find more readable?

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

for envname in ['TMPDIR', 'TMP', 'TEMP']:
    if os.environ.has_key(envname):
        basepaths = validate_paths(path)
        if basepaths:
            break
else:
    basepaths = validate_paths(_tmpdirs)


-Chuck





More information about the Python-list mailing list