使用“print”时出现无效语法?

118 投票
4 回答
335018 浏览
提问于 2025-04-15 11:58

我正在学习Python,但连第一个例子都写不出来:

print 2 ** 100

这段代码会出现 SyntaxError: invalid syntax 的错误

错误指向了第2行。

这是为什么呢?我用的是3.1版本。

4 个回答

8

在Python 3中,print的用法发生了变化。在Python 2中,print是一个语句,而在Python 3中,它变成了一个函数,这就意味着你在使用它的时候需要加上括号。

这里有一份关于Python 3.0的文档,详细说明了这个变化:Python 3.0的更新内容

14

你需要加上括号:

print(2**100)
244

这是因为在Python 3中,他们把原来的print 语句替换成了print 函数

语法现在基本上和以前差不多,但需要加上括号:

来自于"Python 3的新特性"的文档:

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)!

撰写回答