小编典典

python-使用Python 3打印时出现语法错误

python

为什么在Python 3中打印字符串时会收到语法错误?

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

阅读 1179

收藏
2020-02-04

共1个答案

小编典典

此错误消息表示你尝试使用Python 3遵循示例或运行使用Python 2print语句的程序:

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

2020-02-04