I'm assigning a function to a variable like so:
def hello(name):
print "Hello %r \n" % name
king = hello
print "%r, King of Geeks" % king("Arthur")
In the terminal it is returning:
Hello 'Arthur'
None, King of Geeks
What gives?
I'm assigning a function to a variable like so:
def hello(name):
print "Hello %r \n" % name
king = hello
print "%r, King of Geeks" % king("Arthur")
In the terminal it is returning:
Hello 'Arthur'
None, King of Geeks
What gives?
hello()
is printing something, but returns None. (all functions return None
by default unless you explicitly return
something)
>>> result = hello('test')
Hello 'test'
>>> print result
None
If you make hello()
return the text, rather than print it, you'll get the expected result:
def hello(name):
return "Hello %r \n" % name
king = hello
print "%r, King of Geeks" % king("Arthur")
"Hello 'Arthur' \n", King of Geeks
I suggest using New String Formatting instead of %
as well:
print "{}, King of Geeks".format(king("Arthur"))
Your hello
function is print
ing the string it creates, rather than returning it.
Then you try to substitute the return value from calling the function into another string.
Because your hello
function doesn't return anything, it effectively returns None
instead, hence why that gets substituted in. Just change the print
into a return
inside your hello
function and things will work as expected.
You're printing the result of the call to king("Arthur")
, which is None
as it does not return a value.
This also works
def hello(name):
print("hello, %s" % name)
king = hello
king("arthur")
Output
hello, arthur