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

Sco*_*ott 260 python python-3.x

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

>>> print "hello World"
  File "<stdin>", line 1
    print "hello World"
                      ^
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)

Unk*_*own 329

在Python 3中,print 成为一个函数.这意味着您需要现在包含括号,如下所述:

print("Hello World")
Run Code Online (Sandbox Code Playgroud)


bri*_*anz 47

看起来你正在使用Python 3.0,其中print已变成可调用函数而不是语句.

print('Hello world!')
Run Code Online (Sandbox Code Playgroud)


Chi*_*and 28

因为在Python 3中,print statement已经被替换为a print() function,用关键字参数替换旧的print语句的大部分特殊语法.所以你必须把它写成

print("Hello World")
Run Code Online (Sandbox Code Playgroud)

但是如果你在一个程序中编写这个并且使用Python 2.x的某个程序试图运行,它们将会出错.为避免这种情况,最好导入打印功能

from __future__ import print_function
Run Code Online (Sandbox Code Playgroud)

现在你的代码适用于2.x和3.x.

查看下面的示例也是为了熟悉print()函数.

Old: print "The answer is", 2*2
New: print("The answer is", 2*2)

Old: print x,           # Trailing comma suppresses newline
New: print(x, end=" ")  # Appends a space instead of a newline

Old: print              # Prints a newline
New: print()            # You must call the function!

Old: print >>sys.stderr, "fatal error"
New: print("fatal error", file=sys.stderr)

Old: print (x, y)       # prints repr((x, y))
New: print((x, y))      # Not the same as print(x, y)!
Run Code Online (Sandbox Code Playgroud)

来源:Python 3.0有什么新功能?