[Tutor] "=" invalid syntax ?

On Sat, 31 Jan 2004, Tim Johnson wrote:
> > File "./test.py", line 8
> > while (line=fi.readline()):
> > ^
> > SyntaxError: invalid syntax
> >
> > what's the problem?
> > while (line=fi.readline()):
>> '=' is an assignment operator in python.
> '==' is the comparison operator in python.
> use '=='
>> happens to me all the time ....
Hi Tim,
Changing '=' to '==' will make it syntactically correct, but it won't
preserve the intended meaning.
Xuer appears to be using a C-ish syntax: in the C language, it's legal to
say something like:
while((ch = getc(stdin)) != EOF) { ... }
In the C language, assignment is treated as an "expression" that can be
nested within other expressions, so the above C code mixes together an
assigment with a comparison. Very succinct, but also very error prone.
In Python, assignment is treated as a "statement". The thing that
distinguishes a "statement" from an "expression" is that a statement isn't
very nestable within another statement. This prevents certain mistakes
(like using 'assignment' on accident, when we really mean 'equality
test'), but at the cost of being more verbose.
That should explain why we're getting a SyntaxError out of:
> > File "./test.py", line 8
> > while (line=fi.readline()):
> > ^
> > SyntaxError: invalid syntax
because the assignment statement can't nest within the while statement.
How do we fix this? To get the direct effect of
###
while (line=fi.readline()): ## pseudo-C/Python
...
###
with the 'while' loop, we must break it up into separate statements:
###
while 1:
line = fi.readline()
if not line: break
...
###
But this ends up being longer than the equivalent code in C! Is there a
better way to say this?
There's actually an alternative that's available in recent versions of
Python, if we use the 'for' loop:
###
for line in fi:
...
###
This has almost the same effect as the original code, and it scans well
too. It takes advantage of the widespread support of 'iterators' into the
Python language, and here, we treat the file as an iterable object that we
can loop across.
Hope this helps!