I'm learning to program and I am using Python to start. In there, I see that I can do something like this:
>>>> def myFunction(): return 1
>>>> test = myFunction
>>>> test()
1
However, if I try and do the same with print
it fails:
>>>> test2 = print
File "<stdin>", line 1
test2 = print
^
SyntaxError: invalid syntax
Why is print
different than a function I create? This is using Python v2.7.5.
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.
来源:https://stackoverflow.com/questions/20767402/why-cant-i-assign-pythons-print-to-a-variable