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

Michael Torrie torriem at gmail.com
Fri Nov 3 15:15:58 EDT 2017


On 11/03/2017 11:44 AM, Jon Ribbens wrote:
> And that's leading you into confusion, as you've demonstrated.

And indeed I've been led into considerable confusion about the else:
clause over the years. Every time I need to use it, I run a python shell
and try it out to remind myself how it works.  However now with your
mental model, Jon, I think I finally have it! Thank you.

I can't think of any normal circumstance where for/else is useful
without a break.  In fact if you have no break you may as well drop the
else entirely, because the block will always execute.  A linter should
definitely flag this.  One reason to leave it as valid syntax is maybe I
am coding up some skeleton code that I plan to fill in later.  So for
now the loop falls through, but at some future point I'll have finished
the searching code and added the break.  But if it were a syntax error I
don't think that'd be any big deal.

Anyway, thank you again, Jon.  Your explanation and model has greatly
cleared up my confusion, and I think if the docs reasoned along the same
lines it would clear up confusion in most programmers.  Certainly it
appears your line of reasoning is what Guido had in mind when he added
the else block.

Sorry Steven, I think Jon's right in this instance and your reasoning
isn't persuasive.



More information about the Python-list mailing list