Function returns None

I’m having a hard time understanding why my function returns the result I want AND None.

I’ve tried to look through the Control Flow Lessons, but I couldn’t find anything to answer my question.

Here is the code (it’s from the Games of Chance project)

def your_toss(coin_bet):

if coin_bet == 1:

  print ("You bet on Heads")

elif coin_bet == 2:

  print ("You bet on Tails")

elif coin_bet > 2:

  print("You must chose 1 or 2")

#return ""     

print(your_toss(1))

Without the return “” activated in the function, the print will show:
You bet on Heads
None

If I activate the return “” in the function, the print will show:
You bet on Heads
(black row)

your function doesn’t return the result you want? Your function prints the result you want. There is a difference.

if your function purely needs to print, and has no return value, why bother attempting to print the return value?

1 Like

Maybe my wording was a little bit wrong. My fuction gives me the result I want.

My question is about the None part, I’m not sure if that’s ok to be shown in the terminal. And I don’t understand why it is returned it’s returned in the first place.

None is the absence of a return value.

If you don’t want to show it, why print the returned value (or the absence of a return value)?

If your function doesn’t have a return value, its return value is None. If I have

def some_function():
    num = 42

print(some_function())

what is printed is “None” because the function doesn’t return anything. What happens inside the function doesn’t matter to the print call. A function like

def another_function():
    print("Hello")

will work in much the same way. The print statement will print the value returned from the function, None. Because the function also prints, “Hello” will be printed too. You’ll get

"Hello"
None

This is what’s happening with your function when you comment out the return statement. When you uncomment the return statement, now your function returns an empty string which can be printed and just shows up as a blank line.
There are a couple of ways you can change the behavior of your function. First, you can call it without the print statement, changing the call to just your_toss(1) and let the function handle the printing. Another way could be to keep the print statement and change the function so that instead of printing a string like “You bet on Tails”, return it.