On Wed, Jul 22, 2020 at 1:15 PM Paul Sokolovsky <pmis...@gmail.com> wrote:
>
> Hello,
>
> On Wed, 22 Jul 2020 09:45:31 +1000
> Steven D'Aprano <st...@pearwood.info> wrote:
>
> > On Tue, Jul 21, 2020 at 10:07:47PM +0100, Barry wrote:
> >
> > > 1. Because that not what else mean today. Its elif never looped.
> >
> >
> >     py> for x in [1,2]:
> >     ...     print("inside loop")
> >     ... else:
> >     ...     print("elif never looped")
> >     ...
> >     inside loop
> >     inside loop
> >     elif never looped
> >
> >
> > This is why I have long-argued that the keyword here should be *then*
> > not else. The semantics are that the loop executes, *then* the
> > following "else" block executes,
>
> But no, loop executes, *or else* the following "else" block
> executes ;-). That's the logic of founding fathers. After one grasped
> that logic, one comes to appreciate a weird beauty of it. The verdict
> remains the same though: "Do Not Use".
>

There's a buggy construct that I see VERY frequently in my students'
code (which I'll show in Python syntax here, but this can happen in
any language) that closely parallels the actual semantics of Python's
for-else, and showcases its value.

# Find the first two-digit number, or return 99
def find_big_number(pile):
    for number in pile:
        if number > 10:
            return number
        else:
            return 99

It's extremely common to see this "else" attached to its "if" in a way
that prevents the loop from finishing. Now, obviously, in the case
where you're using a "return" as the body of the else, you could just
unindent it as unconditional post-loop code, but that doesn't work for
other examples, and as a general rule, it seems that people like to
think in terms of "if it is what we want, do this, otherwise do that".

And that behaviour is exactly what a for-else loop does.

ChrisA
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/JW6OU5YRQZ7JFZCDDG5DLK2QDVMAFEA3/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to