Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 346
LilahF Avatar asked Dec 24 '13 22:12

LilahF


People also ask

Can I assign print to a variable Python?

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 .

Can print statement assigned to variable?

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.

How do you assign a value to a variable in Python?

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.


1 Answers

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).

like image 147
BrenBarn Avatar answered Oct 21 '22 16:10

BrenBarn