在Python中,“ SyntaxError:调用’print’时缺少括号”是什么意思?

问题:在Python中,“ SyntaxError:调用’print’时缺少括号”是什么意思?

当我尝试print在Python中使用语句时,它给了我这个错误:

>>> print "Hello, World!"
  File "<stdin>", line 1
    print "Hello, World!"
                        ^
SyntaxError: Missing parentheses in call to 'print'

这意味着什么?

When I try to use a print statement in Python, it gives me this error:

>>> print "Hello, World!"
  File "<stdin>", line 1
    print "Hello, World!"
                        ^
SyntaxError: Missing parentheses in call to 'print'

What does that mean?


回答 0

此错误消息表示您尝试使用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!")?

由于“在打印输出中缺少括号”情况是编译时语法错误,因此可以访问原始源代码,因此可以在建议的替换内容中在行的其余部分包含全文。但是,它目前并未尝试找出适合该表达式的引号(这不是不可能的,只是足够复杂以至于尚未完成)。

TypeError募投向右移位运算符也被定制:

>>> 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表达式周围很简单。

This error message means that you are attempting to use Python 3 to follow an example or run a program that uses the Python 2 print statement:

print "Hello, World!"

The statement above does not work in Python 3. In Python 3 you need to add parentheses around the value to be printed:

print("Hello, World!")

“SyntaxError: Missing parentheses in call to ‘print’” is a new error message that was added in Python 3.4.2 primarily to help users that are trying to follow a Python 2 tutorial while running Python 3.

In Python 3, printing values changed from being a distinct statement to being an ordinary function call, so it now needs parentheses:

>>> print("Hello, World!")
Hello, World!

In earlier versions of Python 3, the interpreter just reports a generic syntax error, without providing any useful hints as to what might be going wrong:

>>> print "Hello, World!"
  File "<stdin>", line 1
    print "Hello, World!"
                        ^
SyntaxError: invalid syntax

As for why print became an ordinary function in Python 3, that didn’t relate to the basic form of the statement, but rather to how you did more complicated things like printing multiple items to stderr with a trailing space rather than ending the line.

In Python 2:

>>> import sys
>>> print >> sys.stderr, 1, 2, 3,; print >> sys.stderr, 4, 5, 6
1 2 3 4 5 6

In 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

Starting with the Python 3.6.3 release in September 2017, some error messages related to the Python 2.x print syntax have been updated to recommend their Python 3.x counterparts:

>>> print "Hello!"
  File "<stdin>", line 1
    print "Hello!"
                 ^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print("Hello!")?

Since the “Missing parentheses in call to print” case is a compile time syntax error and hence has access to the raw source code, it’s able to include the full text on the rest of the line in the suggested replacement. However, it doesn’t currently try to work out the appropriate quotes to place around that expression (that’s not impossible, just sufficiently complicated that it hasn’t been done).

The TypeError raised for the right shift operator has also been customised:

>>> 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>)"?

Since this error is raised when the code runs, rather than when it is compiled, it doesn’t have access to the raw source code, and hence uses meta-variables (<message> and <output_stream>) in the suggested replacement expression instead of whatever the user actually typed. Unlike the syntax error case, it’s straightforward to place quotes around the Python expression in the custom right shift error message.


回答 1

不幸的是,旧的xkcd漫画不再完全是最新的。

从Python 3.0开始,您必须编写:

print("Hello, World!")

而且仍然有人要编写该antigravity库:(

Unfortunately, the old xkcd comic isn’t completely up to date anymore.

Since Python 3.0 you have to write:

print("Hello, World!")

And someone has still to write that antigravity library :(


回答 2

语法从Python 2更改为Python3。在Python 2中,

print "Hello, World!" 

可以使用,但是在Python 3中,使用括号作为

print("Hello, World!")

这与Scala等效,与Java差不多。

There is a change in syntax from Python 2 to Python 3. In Python 2,

print "Hello, World!" 

will work but in Python 3, use parentheses as

print("Hello, World!")

This is equivalent syntax to Scala and near to Java.


回答 3

如果您的代码在Python 2和3中都可以使用,则可以通过在程序开始时加载以下代码来实现:

from __future__ import print_function   # If code has to work in Python 2 and 3!

然后,您可以使用Python 3方式进行打印:

print("python")

如果要打印某些内容而不创建新行,则可以执行以下操作:

for number in range(0, 10):
    print(number, end=', ')

If your code should work in both Python 2 and 3, you can achieve this by loading this at the beginning of your program:

from __future__ import print_function   # If code has to work in Python 2 and 3!

Then you can print in the Python 3 way:

print("python")

If you want to print something without creating a new line – you can do this:

for number in range(0, 10):
    print(number, end=', ')

回答 4

在Python 3中,您只能将其打印为:

print("STRING")

但是在Python 2中,不需要括号。

In Python 3, you can only print as:

print("STRING")

But in Python 2, the parentheses are not necessary.


回答 5

基本上,从Python 3.x开始,您需要使用 print括号。

Python 2.x:打印“指环王”

Python 3.x:print(“指环王”)


讲解

print2.x中是一个语句,但在3.x中是一个函数。现在,有很多充分的理由。

  1. 使用Python 3.x的函数格式,当打印多个用逗号分隔的项目时,灵活性更高。
  2. 您不能在语句中使用参数展开。在3.x中,如果有要使用分隔符打印的项目列表,则可以执行以下操作:
>>> items = ['foo', 'bar', 'baz']
>>> print(*items, sep='+') 
foo+bar+baz
  1. 您不能覆盖语句。如果要更改print的行为,则可以在它是一个函数时执行此操作,但在声明时不可以。

Basically, since Python 3.x you need to use print with parenthesis.

Python 2.x: print “Lord of the Rings”

Python 3.x: print(“Lord of the Rings”)


Explaination

print was a statement in 2.x, but it’s a function in 3.x. Now, there are a number of good reasons for this.

  1. With function format of Python 3.x, more flexibility comes when printing multiple items with comman separated.
  2. You can’t use argument splatting with a statement. In 3.x if you have a list of items that you want to print with a separator, you can do this:
>>> items = ['foo', 'bar', 'baz']
>>> print(*items, sep='+') 
foo+bar+baz
  1. You can’t override a statement. If you want to change the behavior of print, you can do that when it’s a function but not when it’s a statement.

回答 6

我还可以补充一点,我知道Python2.7和之间有关语法更改的所有知识Python3,并且我的代码正确编写为as print("string")甚至 print(f"string")

但是经过一段时间的调试后,我意识到我的bash脚本正在像这样调用python:

python file_name.py

这具有默认情况下使用python调用我的python脚本的作用,从而产生python2.7了错误。因此,我将bash脚本更改为:

python3 file_name.py

哪个使用python3来运行修复了错误的脚本。

I could also just add that I knew everything about the syntax change between Python2.7 and Python3, and my code was correctly written as print("string") and even print(f"string")

But after some time of debugging I realized that my bash script was calling python like:

python file_name.py

which had the effect of calling my python script by default using python2.7 which gave the error. So I changed my bash script to:

python3 file_name.py

which of coarse uses python3 to run the script which fixed the error.


回答 7

除了这里的直接答案外,还应注意python 2和3之间的另一个主要区别。官方python Wiki涵盖了几乎所有主要区别,并着重于何时应使用这两个版本。这篇博客文章也很好地解释了当前的python宇宙以及迁移到python 3时仍未解决的难题。

据我所知,您正在开始学习python语言。在继续进行python 3路由之前,您应该考虑上述文章。您不仅需要更改某些语法,还需要考虑哪些包对您可用(python 2的优点)以及可以在代码中进行的潜在优化(python 3的优点) 。

Outside of the direct answers here, one should note the other key difference between python 2 and 3. The official python wiki goes into almost all of the major differences and focuses on when you should use either of the versions. This blog post also does a fine job of explaining the current python universe and the somehow unsolved puzzle of moving to python 3.

As far as I can tell, you are beginning to learn the python language. You should consider the aforementioned articles before you continue down the python 3 route. Not only will you have to change some of your syntax, you will also need to think about which packages will be available to you (an advantage of python 2) and potential optimizations that could be made in your code (an advantage of python 3).