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

Chris Angelico rosuav at gmail.com
Wed Nov 1 22:04:09 EDT 2017


On Thu, Nov 2, 2017 at 12:19 PM, Steve D'Aprano
<steve+python at pearwood.info> wrote:
> On Thu, 2 Nov 2017 08:21 am, Chris Angelico wrote:
>
>> With the 'for' loop,
>> it's a bit more arguable, but I've never seen anything more than a
>> weak argument in favour of 'then'
>
> Thhpptpt!
>
> "else" is an completely inappropriate term that doesn't describe the semantics
> of the statement even a little bit. The argument that it means "else no
> break" is feeble because break is not the only way to exit the loop and
> therefore skip executing the else clause.
>
> It is not even necessarily the most common: I wouldn't be surprised if there
> were more returns out of the middle of a loop than breaks, although I
> wouldn't necessarily predict it either.

I'd say that's plausible, partly because it's easier than messing
around with the else clause. Sometimes, it's easier to just make
another function so you can use 'return' as flow control.

> If we spoke in ordinary English using "else" the way Python uses it for
> looping, we would say:
>
> "Shampoo your hair twice, ELSE apply conditioner and leave for five minutes
> before rinsing."

You wouldn't use 'else' with a simple iteration loop like that -
there's no difference between 'else' and simply having more code after
the loop, unless you have a break.

for _ in range(2):
    hair.shampoo()
condition()
sleep(300)

> "Boil the pasta until it is soft, ELSE drain it and mix in the sauce."

Except that the else keyword doesn't mean that. Here's the nearest I
can come up with as an equivalent:

while pot.water_level:
    pasta.boil()
    if pasta.is_soft(): break
else:
    print("HELP! You boiled the pot dry!")

The else clause happens if you don't break. If you break, you skip the
rest of the loop - including the else. You could use "then" for this,
and it would make sense, but not enough to create a new keyword, and
DEFINITELY not enough to justify changing it now.

Yes, there are arguments against calling this feature "else". But I
stand by my assertion that there are none strong enough to justify a
new keyword.

ChrisA



More information about the Python-list mailing list