LWN.net Logo

When Pythons Attack (O'ReillyNet)

Mark Lutz gives some advice to Python programmers on O'Reilly. "Mark Lutz, coauthor of the recently released Learning Python, 2nd Edition, offers tips, gleaned from his first-hand experience as a Python trainer, on the most common programming and coding mistakes that new Python programmers make. For seasoned Python programmers, Mark offers tips on working with Python's larger features, such as datatypes, functions, modules, and classes."
(Log in to post comments)

Expressions within whiles.

Posted Feb 12, 2004 13:55 UTC (Thu) by jbailey (subscriber, #16890) [Link]

The article says:

Don't embed assignment statements in while loop tests (e.g., while ((x=next() != NULL)). In Python, statements cannot appear where expressions are expected, and an assignment is not an expression.

What is the best solution to this one? I hate the duplicated code of:

x=next()
while(x):
    x=next()

Since, every time I do that, I wind up changing one test and not the other at some point later.

Expressions within whiles.

Posted Feb 12, 2004 14:57 UTC (Thu) by mp (subscriber, #5615) [Link]

I don't know _the_ best solution, but making x support the iteration protocol
and using 'for' instead of 'while' may be useful sometimes.

Expressions within whiles.

Posted Feb 12, 2004 19:15 UTC (Thu) by scruffie (subscriber, #5704) [Link]

The idiomatic way in Python is
while True:
    x = next()
    if not x:
        break
    ...
If you know what next() will return when it's finished, you could use iter:
for x in iter(next, None):
    ...

Copyright © 2004, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds