Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
866 views
in Technique[技术] by (71.8m points)

syntax error - Why am I getting a SyntaxError in the Python interpreter?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...