Why can't I assign python's print to a variable?

[亡魂溺海] 提交于 2019-12-04 04:29:55
BrenBarn

print is a statement, not a function. This was changed in Python 3 partly to allow you to do things like this. In Python 2.7 you can get print as a function by doing from __future__ import print_function at the top of your file, and then you will indeed be able to do test = print.

Note that with print as a function, you can no longer do print x but must do print(x) (i.e., parentheses are required).

In addition to what BrenBarn said about the print function, note that print will not return a value. A statement of course will never return a value (which is why you see that error), but even as a function you will not get the value the function prints as the return value.

Instead, print directly writes something to the output, usually the console. If you want to store the value inside a variable instead, just assign whatever you wanted to print to that variable instead.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!