当我试图在Python中使用print
语句时,它给了我这样的错误。
>>> print "Hello, World!"
File "<stdin>", line 1
print "Hello, World!"
^
SyntaxError: Missing parentheses in call to 'print'
这是什么意思?
这个错误信息意味着你正试图用Python 3来遵循一个例子或运行一个使用Python 2 print
语句的程序。
print "Hello, World!"
上面的语句在Python 3中不起作用。在Python 3中,你需要在要打印的值周围加上小括号。
print("Hello, World!")
"SyntaxError:在调用 'print'时缺少括号 "是Python 3.4.2中新增加的错误信息,主要是为了帮助那些在运行Python 3时试图跟随Python 2教程的用户。
在Python 3中,打印值从一个独立的语句变成了一个普通的函数调用,所以它现在需要小括号。
>>> print("Hello, World!")
Hello, World!
在Python 3的早期版本中,解释器只是报告一个普通的语法错误,而没有提供任何有用的提示,说明可能出了什么问题。
>>> print "Hello, World!"
File "<stdin>", line 1
print "Hello, World!"
^
SyntaxError: invalid syntax
至于为什么print
在Python 3中变成了一个普通的函数,这与语句的基本形式无关,而是与你如何做更复杂的事情有关,比如用尾部的空格而不是结束行来打印多个项目到stderr。
在Python 2中。
>>> import sys
>>> print >> sys.stderr, 1, 2, 3,; print >> sys.stderr, 4, 5, 6
1 2 3 4 5 6
在Python 3中。
>>> import sys
>>> print(1, 2, 3, file=sys.stderr, end=" "); print(4, 5, 6, file=sys.stderr)
1 2 3 4 5 6
从2017年9月的Python 3.6.3版本开始,一些与Python 2.x打印语法有关的错误信息已被更新,以推荐其Python 3.x对应的信息。
>>> print "Hello!"
File "<stdin>", line 1
print "Hello!"
^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print("Hello!")?
由于"Missing parentheses in call to print"案例是一个编译时的语法错误,因此可以访问原始源代码,它能够在建议的替换中包含该行其余部分的全文。然而,它目前并没有尝试在表达式周围加上适当的引号(这并不是不可能的,只是由于足够复杂而没有做到)。
对右移运算符产生的 "类型错误 "也进行了定制。
>>> print >> sys.stderr
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for >>: 'builtin_function_or_method' and '_io.TextIOWrapper'. Did you mean "print(<message>, file=<output_stream>)"?
由于这个错误是在代码运行时提出的,而不是在编译时提出的,所以它不能访问原始源代码,因此在建议的替换表达式中使用元变量(<message>
和<output_stream>
)而不是用户实际输入的内容。与语法错误的情况不同,在自定义右移错误信息中,在Python表达式周围加上引号是很直接的。
从Python 2到Python 3,在语法上有一个变化。 在Python 2中。
print "Hello, World!"
可以工作,但在Python 3中,使用小括号作为
print("Hello, World!")
这与Scala的语法相当,接近于Java。