do...while loops

Remco Gerlich scarblac at pino.selwerd.nl
Tue Feb 6 06:28:13 EST 2001


Dan Parisien <dan at eevolved.com> wrote in comp.lang.python:
> why don't do...while loops exist in python? Is there are better way to get 
> to that functionality?
> 
> e.g.
> file = open(...)
> do:
>         line = file.readline()
> while line != ""
>  
> Do I have to write a PEP or read some more documentation? ;-)

This has been discussed to death, over and over again. Some of the reasons
cited are that the construct is redundant, there is no way to indent it in a
way consistent with the rest of Python, and Guido doesn't like it (all of
those may or may not be true...).

The Python idiom in the general case is:

while 1:
   line = file.readline()
   ...
   if not line:
      break
   ...
   
But in the specific case of reading lines from files, this is neater:

for line in file.readlines():
   ...
   
Which reads the whole file into memory at once. For the case your files are
too big, the upcoming Python 2.1 will have the .xreadlines() method which
works the same way but does not load everything at once.

At the moment, the fileinput module gives that functionality:

import fileinput
for line in fileinput.input("filename"):
   ...
   

HTH.

-- 
Remco Gerlich



More information about the Python-list mailing list