What does return do?


#1

Question

What does return do?

Answer

It sounds silly, but return does literally what it says – it returns something to wherever the function was called in the program. If we consider the square() function in this exercise, for example, it does some calculation with the number given to the function as n, and then returns the final result called squared.
This allows us to do lots of useful things! When we return a value it can be stored in a variable for later use, or used on the spot, or any number of things. It basically makes your function call a usable value!
Take a look at the code below for an example:

def square(n):
  """Returns the square of a number."""
  squared = n ** 2
  return squared


my_number_squared = square(10)
print my_number_squared  # Prints 100 
print square(10)  # Also prints 100!

We not only used the returned value to store a value in a variable, but we also used it with a built in method that takes a value and prints it, print! Pretty handy!


FAQ: Learn Python: Functions - Call and Response
#3

Hi,
I actually still dont understand why do we need Return really !
if you get rid of it you will see that nothing changes, the output still the same! when I call the fuction defined wheather or not I inculde the Return the output still the same.
Can someone explain please !


#4

Agree that the example above outputs 100 twice?

now lets remove return:

def square(n):
  """Returns the square of a number."""
  squared = n ** 2

my_number_squared = square(10)
print my_number_squared  # Prints None
print square(10)  # Also prints None

run the code or see the comments for output. so return does literally what is say, its returns/hands back the values. This is very useful, given squared is a local variable within the function, without return we wouldn’t be able to access it outside the function


#5

True, however, when I try when the example below, taking out the Returndoesnt change anything !
image


#6

because you do nothing with the returned value.

However, its more complicated that that. return is a control flow construct, to pass data around. And not specific for this example, but as programs grow larger, control flow is such important. You need separate functions for maintainability. (you do seriously not want a 10,000 line single file with no function or classes, its a nightmare).

so understanding return is very important, you are going to need it later, a lot.

That is always the problems with these concepts, its not just specific about this exercise, its about the bigger picture. Something which is difficult to explain.