0

in Java, this is valid. multiple assignments in a single statement.

while ((sCurrentLine = br.readLine()) != null) {
                System.out.println(sCurrentLine);
            }

Is there a similar thing thing in python. I tried but I get the following error.

>>> file = open("reverse.py")
>>> while(x=file.readline()!=""):
  File "<stdin>", line 1
    while(x=file.readline()!=""):
           ^
SyntaxError: invalid syntax
brain storm
  • 30,124
  • 69
  • 225
  • 393

3 Answers3

4

Assignment is not an expression in python. Basically while requires an expression and you are giving an statement.

You can check here for detailed explanation.

Community
  • 1
  • 1
moliware
  • 10,160
  • 3
  • 37
  • 47
  • 1
    +10 internets. This is the important point: Assignment is not an expression but a statement, unlike in many other languages. – Hyperboreus Oct 04 '13 at 19:20
  • Full definition copied from the docs: expr_stmt: testlist_star_expr (augassign (yield_expr|testlist) | ('=' (yield_expr|testlist_star_expr))*) – Hyperboreus Oct 04 '13 at 19:31
0

No, there is no such thing.

On the other hand you don't need this kind of syntax with Python. Just iterate over the file object:

with open(filename) as fp:
    for line in fp:
        pass
Matthias
  • 12,873
  • 6
  • 42
  • 48
0

multiple assignments work (though maybe not the way you'd expect):

In [373]: a = b = c = 0x1234

In [374]: a
0x1234

In [375]: b
0x1234

In [376]: c
0x1234

your problem is the while syntax, which is just while(predicate). assignments can't be part of a predicate in python.

however, most of the time, you don't need those sorts of constructs in python, as they are implicit. you can do:

file = open('reverse.py')
for line in file:
    <do something>

and it will automatically terminate at EOF with StopIteration; you don't need to do the manual sentinel checks. Even more pythonic would be to use a context manager:

with open('reverse.py') as file:
    for line in file:
        <do something>

which is like the above, but will also automatically close the file when you are done.

Corley Brigman
  • 11,633
  • 5
  • 33
  • 40