while true: !!!

Alex Martelli aleaxit at yahoo.com
Tue Dec 19 09:12:08 EST 2000

"deadmeat" <root@[]> wrote in message
news:qwu%5.8061$KY1.22030 at news1.rivrw1.nsw.optushome.com.au...
> > This is precisely where having assigment as an expression (like C/C++)
> > is useful :
> > while ( (line = file.readline()) != None ) :
> yuk.. I'd prefer the Pascal way to C's
> while file.readline(line) do
>  // whatever
> however I don't know if variables passed to Python functions can be

The variable will refer to the same object, before and after the
call, no matter what the function does.  The object itself may
be changed, if it's a mutable object.

If the object that 'line' refers to is a string (immutable, in
Python), then you surely cannot do what you desire.

> however the file reading thing is just one example of while 1: so being
> to avoid it in this case is hardly any breakthough.

Of course.  The general idiom, as Knuth said in 1974, is:

    while 1:

        "several" (0 or more)

        if condition: break

        "several" (0 or more)

Unless you're in a special case where either block just
happens to collapse to 0 lines, you can try to hide and
obscure the natural structure of your algorithm (hardly
a clever strategy, that!), but that will not change the
way the algorithm WANTS to be coded.  In Python, it's
not even particularly interesting if the _second_ block
collapses to length 0, as Python has no test-at-end loop,
which is an excellent simplification; only if the FIRST
of the two blocks is zero-length does the
    while 1:
        if condition: break
_naturally_ become
    while not condition:


More information about the Python-list mailing list