How can I return a print function in Python 2.7? In Python 3 you can type return print(True), but in Python 2.7 I get an invalid syntax error when I try return print True. I'm new to Python.
3 Answers
In Python 2.x print is not a function, but a keyword. The possible best solution would be importing 3.x-like print behvaiour as follows:
from __future__ import print_function p = print # now you can store the function reference to a variable p('I am a function now!') >>> I am a function now! def get_print(): return print # or return it :) get_print() >>> <function print> Comments
That's not possible with Python 2.7 because print is not a function, it is a reserved word*. You can easily make a function for it just like this:
def printf(x): print x And then you can do what you wish:
return (printf(True)) But you have to do that renaming.
*That's one of the things that were solved more elegantly on python 3.
Comments
print, being a statement rather than a function in Python 2, cannot be used in this way. Rather, you need to do this:
from __future__ import print_function def foo(): return print(True) foo() 3 Comments
Zaur Nasibov
Why
True in print(True)? oOVolatility
@BasicWolf Cause that was in the original question
Zaur Nasibov
Ah, sorry, my bad. Time for me to go to bed :)
return (print True)printfunction in 3.x; you're returning the result of calling theprintfunction, which is always justNone.return print(but that would not work in Python 2.x)