[Tutor] Why is it...

Terry Carroll carroll at tjc.com
Thu Mar 22 22:07:55 CET 2007


On Thu, 22 Mar 2007, Jason Massey wrote:

> In the interpreter this doesn't work:
> 
> >>> f = open(r"c:\python24\image.dat")
> >>> line = f.readline()
> >>> while line:
> ...     line = f.readline()
> ... f.close()
> Traceback (  File "<interactive input>", line 3
>     f.close()
>     ^
> SyntaxError: invalid syntax

The interactive interpreter was expecting a blank line to end the suite of
the compound statement.  Without the blank line, it interpreted the close
statement to be part of the suite;  and since it's not indented as the
suite should be, it's a syntax error.

The blank line requirement is only in interactive sessions:

      Note that a (top-level) compound statement must be followed by a 
      blank line in interactive mode; this is needed to help the parser
      detect the end of the input.

 http://docs.python.org/ref/interactive.html

> But this does:
> 
> >>> f = open(r"c:\python24\image.dat")
> >>> line = f.readline()
> >>> while line:
> ...     line = f.readline()
> ...
> >>> f.close()
> >>>
> 
> Note the differing placement of the f.close() statement, it's not part of
> the while.

The difference is that this time you gave it the blank line to end the 
suite.




More information about the Tutor mailing list