How to assign a function to a variable then call with parameters in python

Question:

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?

Asked By: Chiko

||

Answers:

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"))
Answered By: Alex L

Your hello function is printing 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.

Answered By: Amber

You’re printing the result of the call to king("Arthur"), which is None as it does not return a value.

Answered By: Yuushi

This also works

def hello(name):
  print("hello, %s" % name)

king = hello
king("arthur")

Output

hello, arthur
Answered By: maček
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.