2

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?

Joachim Isaksson
  • 176,943
  • 25
  • 281
  • 294
Chiko
  • 2,330
  • 4
  • 21
  • 29
  • 1
    Since you do not have a `return` statement, the method returns `None`, which is what you see printed. – Burhan Khalid Jan 08 '13 at 05:21
  • You may not want to be using `%r` as that returns the `repr` of the object, and likely not the string you're expecting. Try replacing that with `%s` (after implementing the suggestions below). – RocketDonkey Jan 08 '13 at 05:25

4 Answers4

8

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"))
Alex L
  • 8,748
  • 5
  • 49
  • 75
1

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.

Amber
  • 507,862
  • 82
  • 626
  • 550
0

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

Yuushi
  • 25,132
  • 7
  • 63
  • 81
0

This also works

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

king = hello
king("arthur")

Output

hello, arthur
maček
  • 76,434
  • 37
  • 167
  • 198