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

I am learning to program and I use Python to run. There I see that I can do something like this:

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

However, if I try to do the same with print , this fails:

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

Why is print different from the function I'm creating? This uses Python v2.7.5.

+7
python variable-assignment function-pointers
source share
2 answers

print is a statement , not a function. This has been modified in Python 3 in part to allow you to do such things. 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 can actually do test = print .

Note that when printing as a function, you can no longer execute print x , but you must do print(x) (i.e. brackets are required).

+18
source share

In addition to what BrenBarn said about the print function, note that print will not return a value. Of course, a statement will never return a value (which is why you see this error), but even as a function you will not get a value that the function prints as a 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 everything you would like to print instead of this variable.

+3
source share

All Articles