什么“SyntaxError:在调用'打印'中缺less括号”是Python中的意思?

当我尝试在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中变成了一个普通的函数,那并没有涉及到语句的基本forms,而是关于如何做更复杂的事情,比如将多个项目打印成尾随空格而不是尾行。

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

由于“调用打印中缺less括号”的情况是编译时语法错误,因此可以访问原始源代码,因此可以在build议的replace中的行的其余部分包含全文。 然而,目前它并没有试图找出适当的引号来expression这种expression方式(这不是不可能的,只是复杂到没有完成)。

为右移运算符引发的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>)"? 

由于在代码运行时引发此错误,而不是在编译时发生,因此无法访问原始源代码,因此在build议的replaceexpression式中使用元variables( <message><output_stream> )无论用户实际input什么。 与语法错误情况不同的是,在自定义右移错误消息中围绕Pythonexpression式引用是很简单的。

在python 3中,只能打印为:

 print("STRING") 

但在python 2中,括号是没有必要的。

从Python 2到Python 3的语法都有所变化。在Python 2中,

  print "Hello world!" will work but 

在python 3中,使用大括号

 print("Hello world!") 

这是相当于scala和java的语法。