what is wrong with this line? while (line = workfile.readline()) != "":

D-Man dsh8290 at rit.edu
Tue May 22 17:52:46 CEST 2001


On Tue, May 22, 2001 at 09:14:41AM -0600, erudite wrote:
| Hey,
|     I'm coming from the Java world to the python world which is probably why
| I'm a little confused as to why this statement doesn't work:

Yep.

| while (line = workfile.readline()) != "":
| 
| when I try to run it I get a :
| 
|   File "srns.py", line 38
|     while (line = workfile.readline()) != "":
|                 ^
| SyntaxError: invalid syntax

The difference :
    In Java (and C and C++) assignment is an _expression_, and as such
    it can occur anywhere an expression can occur (such as the
    condition of a while loop).

    In Python assignment is a _statement_ and can only occur where
    statements can occur, not where an expression is expected.


The proper way to write that loop is:

while 1 :
    line = workfile.readline()

    if line == "" : break

    <rest of loop here>


This organization of the loop allows the advancement (reading a line)
to exist only once.  If you note carefully there is only 1 entrance
and only 1 exit point of the loop.

An alternative way to write the loop:

line = workfile.readline()
while line != "" :
    <rest of loop here>
    line = workfile.readline()

IMO this is a poorer way of organizing the loop due to the redunancy
of the line containing the call to 'readline'.


HTH,
-D





More information about the Python-list mailing list