Loop-and-a-half (Re: Curious assignment behaviour)

Huaiyu Zhu huaiyu at gauss.almadan.ibm.com
Mon Oct 15 19:47:49 EDT 2001


On Fri, 12 Oct 2001 16:55:04 -0700, Jeff Shannon <jeff at ccvcorp.com> wrote:

>while 1:
>    x = next()
>    if x.is_end(): break
>    y = process(x)
>    if not y.is_good_result():
>        raise "not found"

This won't do it.  It will raise "not found" as soon as the first y is not
good result.  Eg, this raises "not found":

x = 0
while 1:
    x += 1
    if not x<10: break
    y = x*3
    if not y > 14:
        raise "not found"
print y

In contrast, proposed syntax

while x = next(); not x.is_end():
    y = process(x)
    if y.is_good_result():
        break
else:
    raise "not found"

will raise "not found" iff all y are not good results.  Note that the 'else'
corresponds to 'while', not 'if'.  (This 'else' syntax exists in Python even
without my proposal.)  For example, the following will print 15:

i = 0
while i+=1; i<10:
    y = x*3
    if y > 14: break
else:
    raise "not found"
print y

I have not found existing way to write this without duplicating the 'y =
x*3' or 'i+=1' parts or using temperary vairables.


>Personally, I think that the construct you are promoting,
>
>while (expression); (condition):
>    (suite)
>
>.... is ugly and non-intuitive, and I would *not* want to use it.  Just my
>opinion, but.....


The part before ";" are statements.  The condition must be an expression,
which is the main point of the proposal.  So the proposal is actually

while (statements) ; (expression) :
    (suite)
else :
    (suite)

I'll write it up sometime.

maybe-easier-to-write-a-pep-than-discuss-it-piecemeal-ly yr's

Huaiyu




More information about the Python-list mailing list