"for/while ... break(by any means) ... else" make sense?

Terry Reedy tjreedy at udel.edu
Wed Jun 29 16:22:03 EDT 2016


On 6/29/2016 6:01 AM, Victor Savu wrote:
> There are many posts trying to explain the else after for or while.

My take: a while statement *is* a repeated if statement, and that is how 
it is implemented.

while condition:
     true()

is equivalent to and implemented in machine language without a native 
while command as

<label> if condition:
    true()
    goto label

An else clause is executed exactly when the condition is false.

This understanding is useful in understanding how and why tail recursion 
is equivalent to and can be converted to a while loop.

def f(n, accum):
     if recurse:
         return f(g(n), h(n, accum))
     else:
         return accum

What does the recursive call do?  It assigns new values to the 
parameters and goes to the top of the code.  Since it is a tail call, 
the old parameter bindings are not needed.  So the above does the same as

def f(n, accum):
     <label> if recurse:
         n, accum = g(n), h(n, accum
         goto label
     else:
         return accum

which is the same, by the above, as

def f(n, accum):
     while recurse:
         n, accum = g(n), h(n, accum
     else:
         return accum

In other words, convert properly formatted tail recursion (where the 
condition is the recurse condition, rather than the terminate condition) 
by replacing 'if' with 'while' and the tail recursive call with 
unpacking assignment.

It is conventional to drop the else:, but it is implicitly still there.

-- 
Terry Jan Reedy




More information about the Python-list mailing list