for / while else doesn't make sense

theherk at gmail.com theherk at gmail.com
Thu May 19 14:47:28 EDT 2016


This is exactly what I'm referencing. We can do mental gymnastics for it to make sense, but remove the `break` in your code and what happens? The logic goes away. The code ends up executing anyway, which is what makes it more like "finally" to me. Although, as Ian pointed out that would cause breakages for the "finally" meaning, because with the break you wouldn't expect it to execute, but we expect "finally" always to execute.

It is a great example for sure, but it only makes sense in specific constructs. I think this is a really interesting topic to which there may not be a better answer.

On Thursday, May 19, 2016 at 10:22:31 AM UTC-7, Ned Batchelder wrote:
> On Thursday, May 19, 2016 at 12:43:56 PM UTC-4, Herkermer Sherwood wrote:
> > Most keywords in Python make linguistic sense, but using "else" in for and
> > while structures is kludgy and misleading. I am under the assumption that
> > this was just utilizing an already existing keyword. Adding another like
> > "andthen" would not be good.
> > 
> > But there is already a reserved keyword that would work great here.
> > "finally". It is already a known keyword used in try blocks, but would work
> > perfectly here. Best of all, it would actually make sense.
> > 
> > Unfortunately, it wouldn't follow the semantics of try/except/else/finally.
> > 
> > Is it better to follow the semantics used elsewhere in the language, or
> > have the language itself make sense semantically?
> > 
> > I think perhaps "finally" should be added to for and while to do the same
> > thing as "else". What do you think?
> 
> For/else has always caused people consternation.
> 
> My best stab at explaining it is this: the else clause is executed if no
> break was encountered in the body of the for loop.  A simple structure
> would look like this:
> 
>     for thing in container:
>         if something_about(thing):
>             # Found it!
>             do_something(thing)
>             break
>     else:
>         # Didn't find it..
>         no_such_thing()
> 
> I think of the "else" as being paired with the "if" inside the loop.
> At run time, you execute a number of "if"s, one for each iteration
> around the loop.  The "else" is what gets executed if none of the
> "if"s was true.  In that sense, it's exactly the right keyword to
> use.
> 
> --Ned.



More information about the Python-list mailing list