PEP-315 ("do" loop)

Jeremy Fincher tweedgeezer at hotmail.com
Tue Feb 17 13:44:54 EST 2004


Wayne Folta <wfolta at netmail.to> wrote in message news:<mailman.55.1076984559.31398.python-list at python.org>...
> 2. It is a very general construct, which might be what is called for. 
> But I wonder if most of the time it would be used to accomplish 
> something like:
> 
> while 1:
>      line = sys.stdin.readline()
>      if line == "\n":
>          break

If you're concerned about the "beauty" of such code, then the
appropriate way to rewrite it is with a custom iterator/generator.

def untilBlankLine(fh):
    line = fh.readline()
    while line != '\n':
        yield line
        line = fh.readline()

And then you can use it like so:

for line in untilBlankLine(sys.stdin):
    doSomething(line)

And remember, you can also create custom iterators with the builtin
iter:

for line in iter(sys.stdin.next, '\n'):
    doSomething(line)

So I really see no need for any more complex looping construct.  The
further we get from encouraging the use of while instead of for, the
better.

Jeremy



More information about the Python-list mailing list