for / while else doesn't make sense

Jon Ribbens jon+usenet at unequivocal.co.uk
Fri May 20 07:55:34 EDT 2016


On 2016-05-20, Steven D'Aprano <steve at pearwood.info> wrote:
> On Fri, 20 May 2016 03:55 am, Jon Ribbens wrote:
>> I guess we should thank our lucky stars that you don't have a time
>> machine then, since that change would very much be one for the worse
>> in my opinion. for...else is perfectly straightforward and clearly
>> the right keywords to use. for...then would be entirely wrong.
>
> "Entirely" wrong? "Clearly" the right keyword? "Perfectly" straightforward?
>
> They are extremely strong words given the posts where *even the defenders*
> of "else" have admitted that it is a hard keyword to understand. But that's
> okay. Maybe you've thought of something the rest of us haven't, and have an
> entire consistent mental model of for...else that is easy to understand and
> makes it "perfectly straightforward and clearly the right keyword".
>
> Can you explain your model which makes "else" appropriate?

Certainly. "else:" is (almost?) invariably used in the situation where
you are iterating through something in order to find a value which
matches a certain condition. So the "for:" block means "find this
value" and the "else:" means "else do this".

> In my experience, some people (including me) misunderstand "for...else" to
> mean that the else block runs if the for block *doesn't*. It took me the
> longest time to understand why this didn't work as I expected:
>
> for x in seq:
>     pass
> else:
>     print("seq is empty")
>
> because like many people, my mental model was "the for block runs, OR ELSE
> the else block runs". This *incorrect* model seems like it works: if you
> set seq=[], say, it prints "seq is empty" as expected.
>
> But its wrong: set seq=[1, 2, 3], and it *still* prints "seq is empty". My
> model of what was going on was faulty.

The problem there is that the mental model is *completely* wrong.
"else:" has nothing at all to do with the number of values in the
iterated sequence.

> I never would have thought of that model if it had been called "then":
>
> for x in seq:
>     pass
> then:
>     print("executes after the for block completes")

I would find that very confusing. "then:" makes it sound like
executing that block is the usual case, when in practice it is
usually the exception - the fallback code if the expected value
was not found.



More information about the Python-list mailing list