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

Terry Reedy tjreedy at udel.edu
Sun Mar 20 23:19:54 EDT 2016


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?

 > and I'm not the only person to have made it.
 > This (wrong, incorrect) interpretation

To me, this is disrespectful of other people.

 > 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.


>
> 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.

I know I am not going to convince you, but please don't call me 'wrong' 
for seeing why 'else' makes sense and for understanding how 'while' is 
constructed from 'if' and 'jump'.  The essential difference between an 
if statement and a while statement is the jump back that causes a repeat 
of the test.

-- 
Terry Jan Reedy



More information about the Python-ideas mailing list