[Python-ideas] Nudging beginners towards a more accurate mental model for loop else clauses
ncoghlan at gmail.com
Sun Jun 10 15:36:43 CEST 2012
On Sun, Jun 10, 2012 at 10:04 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> We have anecdotal evidence that many people expect that for/else will
> execute the else clause when the for loop is empty.
> We have no anecdotal evidence, or any other evidence, that anyone excepts
> that the else clause runs if you return out of the loop.
Right. We also need to remember that this entire discussion started
with a complaint regarding an apparent internal inconsistency in the
language, because the else clauses on if statements and loops don't
mean exactly the same thing. When you read the tutorial, it introduces
the first two forms together, but the third form (try/except/else)
doesn't show up until a later chapter on exception handling. This was
quite possibly one of the factors leading people to make a perfectly
reasonable intuitive leap that happens to be wrong.
All my docs addition is designed to do is discourage readers from
making that incorrect intuitive leap. They will still need to learn
how the else clauses interact with other constructs, like exceptions
and early returns, but those details aren't relevant to building a
fence across the tempting-but-wrong path from "if <iterable>/else" to
"for x in <iterable>/else".
It's a tricky educational problem to be sure, and if it wasn't for
backwards compatibility requirements, there would be a strong
temptation to just drop the else clause from loops entirely. The
versions that use sentinel values instead aren't *that* complicated,
and have the virtue of being explicit. However, that's not going to
happen (it would break too much code without a sufficiently compelling
justification), so making small tweaks to the relevant tutorial docs
(that will hopefully be picked up by Python instructors and other
learning and teching resources) is a reasonable way forward.
Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
More information about the Python-ideas