为什么我在 Python 解释器中收到 SyntaxError 错误? [英] Why am I getting a SyntaxError in the Python interpreter?

查看:60
本文介绍了为什么我在 Python 解释器中收到 SyntaxError 错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我从 .py 文件中尝试此代码时,此代码有效,但在命令行解释器和 Idle 中失败.

<预><代码>>>>尝试:... fsock = open("/bla")... 除了 IOError:...打印捕获"...打印继续"文件<stdin>",第 5 行打印继续"^语法错误:无效语法

我使用的是 python 2.6

解决方案

在 Python 3 中,print 是一个函数而不是一个语句,所以你需要在参数周围加上括号,如 print("continue"),如果您使用的是 Python 3.

然而,插入符号指向的位置比 Python 3 更早,因此您必须改用 Python 2.x.在这种情况下,错误是因为您在交互式解释器中输入了它,它需要一点帮助"才能弄清楚您要告诉它什么.在前一个块之后输入一个空行,以便它可以正确地解读缩进,如下所示:

<预><代码>>>>尝试:... fsock = open("/bla")... 除了 IOError:...打印捕获"...(一些输出显示在这里)>>>打印继续"

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

解决方案

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"

这篇关于为什么我在 Python 解释器中收到 SyntaxError 错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆