开发者

Why am I getting a SyntaxError in the Python interpreter?

开发者 https://www.devze.com 2022-12-25 04:57 出处:网络
This code works when I try it from a .py file, but fails in th开发者_运维问答e command line interpreter and Idle.

This code works when I try it from a .py file, but fails in th开发者_运维问答e 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


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"


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.


Try this one in the interpreter:

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

print "continue"

Important here is the empty line after the indentation. 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 separated by blank lines. Additionally the blank line (two new line characters) indicates the end of the block and that the interpreter should execute it.


Like if/else or for or while, try/except is a compound statement. In a Python shell prompt, statements after control keywords: ... need to be indented because the statement or compound statement is executed one by one. Your last print("continue") is aligned with the top-level try: and considered another statement hence syntax error. If you want to test out try/except/else/finally interactively, you can wrap them in a function:

>>> def t():
...     try:
...             print(x)
...     except:
...             print('exception')
...             return
...     finally:
...             print('finally')
...     print('continue')
...     print('end function t()')
...
>>> t()
exception
finally
>>> x = 99
>>> t()
99
finally
continue
end function t()
>>>

This was done with Windows python shell. When I tried on PyCharm IDE python console, it allows one more statement after the compound statement to execute.

>>> n = 0
>>> while n!= 5:
...    n+=1
... print('n = {}'.format(n)) 
n = 5   # no syntax error
>>>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号