Behavior of the for-else construct

Chris Angelico rosuav at gmail.com
Thu Mar 3 22:41:32 EST 2022


On Fri, 4 Mar 2022 at 14:37, Avi Gross via Python-list
<python-list at python.org> wrote:
>
> That is one way to look at it, Jach. Of course, a particular loop may have multiple break statements each meaning something else. The current implementation makes all of them jump to the same ELSE statement so in one sense, I consider the ELSE to be associated with the loop as a whole. Sometimes the loop may not even have a break statement and yet the dangling ELSE seems to be accepted anyway.
>
> Some languages allow you to break out of deeply nested loops by jumping up two or more levels, perhaps to a label and are more of a goto. I shudder to think how that would work if each loop had an ELSE dangling.
>

It would happen exactly the same way. I don't know why you're so
afraid of the else clause. It's simply part of the loop body, and if
you break out of the loop body, you skip it. If Python had a way to
break out of multiple loop bodies at once, it would skip the else
clauses of any that you break out of.

This is not complicated. You can argue that it could be better named
(but honestly, I'm not a fan of any of the other proposed names
either), but the concept, at its heart, is a simple one.

ChrisA


More information about the Python-list mailing list