views:

118

answers:

3

This code works when I try it from a .py file, but fails in the command line interpreter and Idle.

>>> try:
...     fsock = open("/bla")
... except IOError:
...     print "Caught"
... print "continue"
  File "<stdin>", line 5
    print "continue"
        ^
SyntaxError: invalid syntax

I'm using python 2.6

+4  A: 

With Python 3, print is a function and not a statement, so you would need parentheses around the arguments, as in print("continue"), if you were using Python 3.

The caret, however, is pointing to an earlier position than it would be with Python 3, so you must be using Python 2.x instead. In this case, the error is because you are entering this in the interactive interpreter, and it needs a little "help" to figure out what you are trying to tell it. Enter a blank line after the previous block, so that it can decipher the indentation properly, as in this:

>>> try:
...     fsock = open("/bla")
... except IOError:
...     print "Caught"
...
(some output shows here)
>>> print "continue"
Peter Hansen
+2  A: 

You need to leave a blank line to close the except block. The ... indicates it is still trying to put code in that block, even though you dedent it. This is just a quirk of the interactive interpreter.

Mike Graham
+1  A: 

Try this one in the interpreter:

try:
    fsock = open("/bla")
except IOError:
    print "Caught"

print "continue"

Important here is the empty line after the intendation. I'm using the python 2.6 interpreter and it throws the same Syntax error as you.

This is because the interpreter expects single blocks seperated by blank lines. Additionally the blank line (two new line characters) indicates the end of the block and that the interpreter should execute it.

Philip Daubmeier