replacing `else` with `then` in `for` and `try`

Skip Montanaro skip.montanaro at gmail.com
Wed Nov 1 21:49:39 EDT 2017


I don't know. The word "then" doesn't connote different ways of exiting a
loop to me ("else" doesn't really either, I will grant you that, but it's
what we have). Here's how I would read things:

   - *while* some condition holds, execute the loop, possibly breaking out,
   *then* do some finishing work
   - *for* each element in some sequence, execute the loop, possibly
   breaking out, *then* do some finishing work

In neither case does it seem to me that you execute the finishing work only
if you break out of the loop, but not if the loop terminates when the while
condition becomes false or the for loop's sequence is exhausted. You might
consider that while/then or for/then actually reads too much like English,
fooling you into interpreting it as English, opening you up to ambiguity.
You might argue that "else" doesn't either, but it has the strangely nice
property of actually being a bit clumsier to read, forcing the reader to
learn and apply the precise rules of the programming language instead of
infer the more ambiguous rules of English. Either way, we are down to two
imperfect solutions, and have a case of tomato, tomahto, I think.

If I was starting with a clean sheet of paper, I might put the raise and
except keywords to work, and add a LoopExit exception:

while some condition holds:
    blah blah blah
    if some other condition rears its ugly head:
        raise LoopExit
    blah blah blah
except LoopExit:
    execute exceptional code

English and other natural languages aren't precise enough to serve as
programming languages. Neither are programming languages fluid enough that
we can always expect them to read naturally. There will always be cases
like this where there is no perfect solution. Other examples I can think of
are the if/else expression added to the language relatively recently (never
really reads well to me, though I agree it can be handy), or all the
proposals for switch/case/computed goto statements which litter the Python
PEP cemetery. The desire to add such a statement has been very strong at
times (there is a powerful desire from a performance perspective to have
something akin to C's switch statement), but nothing ever worked well
enough to be accepted.

Skip



More information about the Python-list mailing list