0

I am a little confused why the return statement won't work if I'm calling a function but will when I am printing it. Below is the example of code I worked with.

def get_favorite_food(): 
     food = input("What's your favorite food?")
     return 'Your favorite food' + ' ' + food + ' ' + 'is ready!'

When I try to run:

get_favorite_food()
>>>
Whats your favorite food?Macaroni

Compared to:

print(get_favorite_food())
>>>
Whats your favorite food?Macaroni
Your favorite food Macaroni is ready! 

I apologize if I am using incorrect phrasing in my question. Please correct me so I could rephrase the question for myself and others!

Rohit
  • 23
  • 4
  • 1
    It might be a simple question, but it is at least formatted well. So points for trying :) – QuantumMecha Oct 20 '21 at 04:52
  • It helps a little but I am having trouble relating it to my problem of running the call function get_favorite_food() vs. running print(get_favorite_food()) edit: IT MAKES SENSE. I had to assign a variable to the function, which stores the return value just as they explained in the dictionary question. – Rohit Oct 20 '21 at 05:05

1 Answers1

2

When you are calling a function that returns something, you are supposed to assign a variable to the function call which would store the return value.

def get_favorite_food(): 
     food = input("What's your favorite food?")
     return 'Your favorite food' + ' ' + food + ' ' + 'is ready!'

result = get_favorite_food()
print(result)

In the case of printing the function call, the returned value need not be stored it is directly printed.

  • Thank you!! I didn't realize printing the function call will directly print the return statement, whereas calling it without assigning a variable wouldn't because it doesn't store the return. This I'm assuming is because of "garbage collection" right? – Rohit Oct 20 '21 at 05:10
  • 1
    @Rohit Yes, but that's true of almost every programming language. You can call a function and ignore its return value if you want. Or you can store the return value in a variable, or you can print it, or log it, or pass it to another function as a parameter, etc. Or _anything_ you can think of doing with a returned value, including doing nothing. – aneroid Oct 20 '21 at 05:31
  • 1
    Yes, it is correctly explained by @aneroid. – Himanshu Pingulkar Oct 20 '21 at 14:29