for / while else doesn't make sense

Ned Batchelder ned at nedbatchelder.com
Thu May 19 13:22:16 EDT 2016


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