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.
To assign the output of the print() function to a variable:Remove the call to the function and assign the argument you passed to print() to the variable. The print() function converts the provided value to a string, prints it to sys. stdout and returns None .
The print statement also works with variables. In each case the result is the value of the variable. Variables also have types; again, we can ask the interpreter what they are. The type of a variable is the type of the value it refers to.
The assignment operator, denoted by the “=” symbol, is the operator that is used to assign values to variables in Python. The line x=1 takes the known value, 1, and assigns that value to the variable with name “x”. After executing this line, this number will be stored into this variable.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With