1

When I run the below code:

def heart_value(name1,name2,name3):
    if name1 == "Rachel":
        return print("So you are Rachel!")
    elif name2 == "Rachel":
        print("Ah, so the second person is Rachel.")
        return print('Right?')
    elif name1 != 'Rachel':
        return print('So Rachel is not the first person.')
    else:
        return print('ok')

print(heart_value("Rachel","Rachel","Mike"))

It gives me as follows:

So you are Rachel!
None

Why does it also print None?

Kate Orlova
  • 3,225
  • 5
  • 11
  • 35
Rachel Kim
  • 85
  • 5
  • 5
    Because you are printing the output of another `print` function. You can avoid that by just returning the string, not the `print` function. – aminrd Jan 07 '20 at 18:26
  • 1
    `print` prints something to the screen as a `side effect.` The return-value of `print()` is always `None`, because the print function does not return a value like the `sum` function does for example – Max Power Jan 07 '20 at 18:28
  • 1
    I don't know who voted this question down but just my two cents, it does not deserve to be voted down (hence my offsetting vote-up). In general I think if you vote-down a new user you should probably offer an explanation of why. It's not particularly helpful for a new user to get vote-downs with no elaboration. – Max Power Jan 07 '20 at 18:30

2 Answers2

1

The print function does not return a value. You need to just return the string return '<string>', not return print('<string>').

The reason it is printing 'None' is because you are calling print() on the value the function returns (which is None) so that value therefore appears in the console.

i.e.

if name1 == "Rachel":
    return "So you are Rachel!"
elif name2 == "Rachel":
    return "Ah, so the second person is Rachel. \n Right?"
elif name1 != 'Rachel':
    return 'So Rachel is not the first person.'
else:
    return 'ok'

print(heart_value("Rachel","Rachel","Mike"))
Teymour
  • 1,832
  • 1
  • 13
  • 34
0

The print() function performs an action (printing to the console), but doesn't return anything.

So when you use the statement return(print("ok")), the return function calls the print("ok") function, which prints the text "ok" in the console, but doesn't return anything to the return() function, which means a value of None is passed back to the function that originally called heart_value().

What you need to do is return() the string object itself ("ok"). That way, when you print() the function heart_value(), the print() statement will evaluate the function, get a string object, and print that.

evamvid
  • 831
  • 6
  • 18
  • 40