while true: !!!

Peter Hansen peter at engcorp.com
Mon Dec 11 08:42:35 EST 2000


Jaroslav Gergic wrote:
> 
> one thing I dislike in many Python tutorials is
> the style of infinite 'while' loop with 'break' statements:

[Rewrote original for compatibility with other examples:]

while 1:
   line = fh.readline()
   if not line: 
       break
   ... do something ...

> I hate it so much I prefer to write something like this:
> 
> line = fh.readline()
> while(line != ""):
>   ... do something ...
>   line = fh.readline()
> 
> OK, it is ugly to write the same line of code twice,
> but 'while true' or 'while 1' is very non-programmer construction
> it smells like VisualBasic GOTO.
> 
> Do you know better construction to avoid both - duplicate lines
> and horrible 'while 1' construction?
> 
> Something like:
> 
> while( "" != (line = fh.readline()) ):
>   ... do something ...

IMHO, you should evolve your sense of 'what is right' and accept that
the simpler style is better.  Both of the alternatives you suggest are
worse than the original!  

The former has the repetitive line of code which, while perfectly
correct, is as you say "ugly" (in that it is more likely to give trouble
during maintenance, and took a little longer to type, but that's about
the only reason).

The latter is just plain grim: C code written in Python! :)  A
confusing, compressed mess, useful only in an obfuscation contest or
where you print a lot and paper is expensive...

A clear advantage of the original is that it is much more readable and
is generally considered more "Pythonic" than the others.  I used to have
the same objections you do to this style, but after a few months of
using Python and considering the arguments in favour of the simpler
form, I learned was I believe was the error of my ways. :)  IMHO, as I
said.



More information about the Python-list mailing list