for / while else doesn't make sense

David Jardine david at jardine.de
Thu May 19 15:49:31 EDT 2016


On Thu, May 19, 2016 at 11:47:28AM -0700, theherk at gmail.com wrote:
> 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. 

Quite.  What would the code mean?  Why would you use "else" if you were
always going to drop out of the end of the loop anyway?  You need it in
a situation where you're "hoping" to find something: meet the 6.30 train
at the station, look at each passenger that gets off and if one is
wearing a pink carnation in his/her buttonhole go off together and live 
happily ever after.  But when the last passenger has got off and you 
haven't seen a pink carnation?  That's where the "else" clause comes in.
You hope you won't need it.

> [...]

> On Thursday, May 19, 2016 at 10:22:31 AM UTC-7, Ned Batchelder wrote:
> > 
> > [...]
> > 
> > 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.
> > 

Cheers,
David



More information about the Python-list mailing list