尝试排除语法错误

try except syntax error

下一个代码有问题。

try: 1+1
except Exception as exception: pass
1+1
try: 2+2
except Exception as exception: pass

我在提示中得到的结果是

... ...   File "<stdin>", line 3
    1+1
    ^
SyntaxError: invalid syntax
>>> ... ... ... 4

但是接下来的代码执行没有错误。

try: 1+1
except Exception as exception: pass

try: 2+2
except Exception as exception: pass

我的 sys.version_info 是:

sys.version_info(major=2, minor=7, micro=3, releaselevel='final', serial=0)

为什么会出现语法错误?

使用交互式提示时,块(如try/except块)和下一个独立命令之间需要有一个空行。这仅在 REPL 中,当 运行 一个 .py 文件时,它不是必需的。