[Python-ideas] Control Flow - Never Executed Loop Body

Steven D'Aprano steve at pearwood.info
Mon Mar 21 09:29:52 EDT 2016


On Sun, Mar 20, 2016 at 11:19:54PM -0400, Terry Reedy wrote:
> On 3/20/2016 9:32 PM, Steven D'Aprano wrote:
> 
> > I understood from the keyword that "else" ran *if the for block
> > didn't*, i.e. when the loop iterator is empty.
> > A perfectly natural mistake to make,
> 
> Why is the truth a mistake?

It's not the truth. The else block does *not* only run if the for block
doesn't run. It runs regardless of whether the loop iterable is empty or 
not.


> > and I'm not the only person to have made it.
> > This (wrong, incorrect) interpretation
> 
> To me, this is disrespectful of other people.

It's a statement of fact. I have seen other people make the same mistake 
I made: interpreting the "else" clause as only running if the loop 
iterable is empty. People have been mislead by the keyword. What's 
disrespectful about pointing this out?


> > matches the most common
> > and familiar use of "else", namely in if...else statements:
> 
> >if ...:
> >     a
> >else:
> >     b
> >
> >
> >You can get a, or b, but not both. In English, "else" represents an
> >alternative. This does not come even close to matching the behaviour of
> >for...else, which (in the absense of a "break" executes a *and* b,
> >rather than a *or* b:
> 
> Block a may never be executed.  In any case, once it is, the loop starts 
> over, the test is repeated, and either a or b is executed.

It's an IF...else statement. There's no loop.


> >for ...:
> >     a
> >else:
> >     b
> 
> I see it differently.  For both while and for, block b is the 
> alternative to executing a, when the condition (explicit in 'while', 
> implicit in 'for) is false, just as in an 'if' statement.

That's not what for...else does. Try it with an empty sequence and a 
non-empty sequence:

for x in [1,2]:  print("inside for block")
else: print("inside else block")

for x in []:  print("inside for block")
else: print("inside else block")


BOTH the empty and non-empty cases print "inside else block". It is 
certainly not "the alternative".




-- 
Steve


More information about the Python-ideas mailing list