gpt4 book ai didi

python - 为什么我不能将 python 的打印分配给变量?

转载 作者:太空狗 更新时间:2023-10-29 21:16:03 25 4
gpt4 key购买 nike

我正在学习编程,我正在使用 Python 开始。在那里,我看到我可以做这样的事情:

>>>> def myFunction(): return 1
>>>> test = myFunction
>>>> test()
1

但是,如果我尝试用 print 做同样的事情,它会失败:

>>>> test2 = print
File "<stdin>", line 1
test2 = print
^
SyntaxError: invalid syntax

为什么 print 与我创建的函数不同?这是使用 Python v2.7.5。

最佳答案

print is a statement ,不是函数。这是 changed in Python 3部分是为了让你做这样的事情。在 Python 2.7 中,您可以通过在文件顶部执行 from __future__ import print_function 将 print 作为函数获取,然后您确实可以执行 test = print

请注意,将 print 作为函数,您不能再执行 print x,而必须执行 print(x)(即,需要括号)。

关于python - 为什么我不能将 python 的打印分配给变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20767402/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com