Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #110787

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

From Terry Reedy <tjreedy@udel.edu>
Newsgroups comp.lang.python
Subject Re: "for/while ... break(by any means) ... else" make sense?
Date 2016-06-29 16:22 -0400
Message-ID <mailman.115.1467231752.2358.python-list@python.org> (permalink)
References <CAGtOLTe8VOnW6zbQSpoCwLL8Hj=cvF6wZ7wx-gxO=9-bQQ0fMw@mail.gmail.com> <nl1alp$baj$1@ger.gmane.org>

Show all headers | View raw


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

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: "for/while ... break(by any means) ... else" make sense? Terry Reedy <tjreedy@udel.edu> - 2016-06-29 16:22 -0400

csiph-web