How does `Return` work?

Hi, I honestly think the explanation given under Return is very confusing and not easily understandable. I have been stucked for 2 days now trying to understand it. But the more i read it, the more i get confused. It actually seems that RETURN in itself is a simple and straight forward concept, but honestly, your explanation of it at Codeacademy makes it complicated. I can move forward here and i really need help from someone who can assist with a better explanation within the context of Codeacademy’s examples. I am a beginner without any IT background

8 Likes

When a return statement is reached:

  1. The expression to the right of the word return is evaluated to produce a value

  2. That value is assigned (“returned”) to the calling statement, where it may be assigned to a variable, or passed as an argument to a parameter of another function (such as print(), or itself used as a value in an expression.

  3. The function containing return halts: it immediately stops running, and it is removed from the call stack (the interpreters “short-term memory”) until it is called again. Its local variable values are gone forever. No statement after return will be reached.

Some examples:

def sq(x):    
    return x**2

def half(x):
    return x/2

def circle_area(diameter):
    return 3.14 * sq(half(diameter))

x = 6

sq(x)  # value is returned to this call, but not used for anything; the value is lost.
print(sq(x))   # Now the value is used as argument for print()
q = 3 * sq(x)  # Here it is used as a value in an expression
print(q) 
print(circle_area(x))   # Here the value returned from half() is used as argument to sq()

Output:

36
108
28.26
14 Likes

6 posts were split to a new topic: I don’t understand the instructions?

first of all the answer to your question is “No” its not necessary to add a return statement at the end of any functions . But framing the answer is somewhat difficult.
The ‘return’ statement can be used in many ways
you can even add a blank return statement in a void function where you dont need to (its not necessary)
You can also add a return statement many times in a function
you can use to return value in between the execution of the function
and many more:slightly_smiling_face::slight_smile:

1 Like

I still have problems understanding the “Return” concept especially in the light of the way it is explained in the lesson here. The more i read it, the more i get confused. I have been stucked here for more than 2 weeks and honestly i am already frustrated, Please i need a very simple and detailed explanation using same example in the lesson. One of my major confusion is the use of the word “result”-Is this a variable? Are we going to always have “result=??? as a variable in a function that has “return”?” I am not clear on what is meant by “return” terminates the body of a function. why do we need return? Please i am not just clear on all these. i will rather advise that codeacademy update this session and explain the concept in a better and simpler manner. I must also say the use of “divide_by_four” is a major part of the confusion. Can you also explain why you have “result” as part of the body? Please i need urgent help in order to be able to move forward. Thank you

6 Likes

First, and most important, you must differentiate a function from a function call:

  • You have a function, which is a series of lines beginning with a function header
    def function_name():
    … often containing some variable names (parameters) within the parentheses. After that there are lines that are indented, that comprise the function body. (The function body may or may not contain a return statement.)

  • Then, completely separately, you have a calling statement, or function call. The calling statement (obviously) calls the function, which means that it tells the function to run, and also tells it what values (arguments) to assign to those parameters.

Now. Here’s the magic: When the calling statement runs the function, the return statement returns the value calculated by the function to the calling statement, which can then assign that value to a variable. And that is what result is: a variable to which the returned value is assigned. That variable, result, can then (for instance, as it is here) be used to print the value.

Please note that result is not a part of the body. It is part of the function call. The body has but one line, return input_number/4

If, for some reason, you wanted to divide by a different number than 4 if, say, input_number had a certain value, you might have multiple return statements:

def divide_by_four(input_number):
     if input_number > 80:
         return input_number/8
     if input_number > 40:
         return input_number/4
     if input_number > 20:
         return input_number/2

Then if input_number is 100, the function will get to the first ‘if’, then say, “yes, it is greater than 80”, and will return 80/8, or 10.0. And then the function stops!! So even though 100 is also greater than 40 and 20, those lines will never be reached. That is what “return terminates the body of a function” means.

25 Likes

Precisely what it is. The call to the function is made in the expression, and the return value is assigned to the variable.

Consider this slightly advanced function that returns a function, not a value…

>>> def quadratic(a, b, c):
    return lambda x: a * x ** 2 + b * x + c

>>> 

In maths we would recognize this as the general form of a quadratic equation in one variable, x. a cannot be zero, but b and c can be, and when they are, those two terms cancel out and the return value is the square of x.

We can write a function that will solve for x in any function we pass it…

>>> def solution(f, x):
    return f(x)

>>>

Below we first assign the returned function from quadratic() to a variable.

>>> func = quadratic(1, 0, 0)
>>> 

and now we can pass that and a value for x to our solution function to solve for x…

>>> solved = solution(func, 4)
>>> print (solved)
16
>>> 

return in both cases gives something back to the caller (the call expression), either another function, or a value.

1 * x ** 2 + 0 * x + 0

becomes,

x ** 2

so that 4 ** 2 is 16.

Don’t let the complexity throw you off. It merely demonstrates how return works and what can be returned, namely any object.

In Python, everything is an object whether a function, a data structure, or a value.

4 Likes

I am short of words. i don’t even know how to express my relief. Thank you so much. :blush: . The explanation is more than amazing and easily comprehensible. now i can progress.

5 Likes

I am always amazed with the way you are always on top of it for all student. Thank you very much for taking out time to explain. I am now clear on all front

4 Likes

hello,even i m a beginner,but see, return is very simple it just returns the actual value or the answer for whatever operations we carry out ,such as finding out difference between two numbers or years.whatever is the difference will be returned by the function when we say or include return statement . the use of return statement is just for storing our answers or output in a particular variable,that can be used later with ease.including return is not always necessasry ,it depends upon our requirement .so far as divide_by_4 concept is concerened,it has used return to get the value from the first operation that is to divde 16 by 4 which gives 4 .now this value 4 is stored in result variable ,in the second case that is to divbide 4 by which is 1,the previous result is used which was already 4 ,so u get 1 . it looks complicated its because of many commas and + signs.just replacing of the values have been done .just go through it carefully,u will understand it

1 Like

I am also confused by the Return statement, and I read through all the messages here to understand it better. Still have 1 question:

In this exercise, I was required to :

Add a line to return age .

def calculate_age(current_year, birth_year):
(space, space) age = current_year - birth_year
(space, space) return age ## why need the return statement?
my_age=calculate_age(2049,1993)
dads_age =calculate_age(2049,1953)
print("My age is : “+str(my_age)+” and my dad’s age is : "+str(dads_age))

==========================================

But “age” is never called elsewhere, then why do I need to put it inside the function ?
Without “return age”, I can still get the correct answer.

Tkx.

It won’t be called elsewhere since it is local to the function, only. Outside of the function, it becomes my_age and dads_age respectively on return from each call to the calculate_age function.

return is important when we want to hand a result back to the caller.

Hi Roy

Tkx, but I can get the same results even with the return statement.

So is it just for the exerice that I need to put it there, in future, it will be important in other programming?

Matthew Chiang

1 Like

What happens when you remove the return statement?

my_age    =>  None
dads_age  =>  None

return is an integral part of functions as it gives us a channel to the caller by which data can be passed back.

Got it, many tkx for your fast response.

Can move on to the next!

Matthew Chiang

1 Like

Thank you! I like to read the suggested forum questions to make sure I understand a topic, and even though I figured out the problem, the instruction didn’t seem straightforward. These answered helped me a lot. Thanks, again!

1 Like

I’ve read everything but still I didn’t understand what “return” is. Is there any website for it? Maybe I should see more samples.

Hello, i can understand your frustration . I was exactly where you are now. Kindly take a deep breadth and patiently follow the response to my question on same concern as responded by @patrickd314

First, and most important, you must differentiate a function from a function call :

  • You have a function , which is a series of lines beginning with a function header
    def function_name():
    … often containing some variable names ( parameters ) within the parentheses. After that there are lines that are indented, that comprise the function body . (The function body may or may not contain a return statement.)
  • Then, completely separately, you have a calling statement , or function call . The calling statement (obviously) calls the function , which means that it tells the function to run, and also tells it what values (arguments) to assign to those parameters.

Now. Here’s the magic: When the calling statement runs the function, the return statement returns the value calculated by the function to the calling statement, which can then assig n that value to a variable. And that is what result is: a variable to which the returned value is assigned . That variable, result , can then (for instance, as it is here) be used to print the value.

Please note that result is not a part of the body. It is part of the function call. The body has but one line, return input_number/4

If, for some reason, you wanted to divide by a different number than 4 if, say, input_number had a certain value, you might have multiple return statements:

def divide_by_four(input_number):
     if input_number > 80:
         return input_number/8
     if input_number > 40:
         return input_number/4
     if input_number > 20:
         return input_number/2

Then if input_number is 100, the function will get to the first ‘if’, then say, “yes, it is greater than 80”, and will return 80/8, or 10.0. And then the function stops!! So even though 100 is also greater than 40 and 20, those lines will never be reached . That is what “return terminates the body of a function” means.

1 Like

You see, when you write your code, return means you are telling the computer what to do. One example could be say if you want to tell the computer to multiply 8 by 9, you would say return 8 * 9. This can be used after conditional statements too. I also had trouble understanding what return means, but I then figured it out.

While the function will return 72, it is not the return that tells the computer to multiply 8 by 9. 8 * 9 does that. The computer sees 72, and since it is given in a return statement, it carries out that action, sending 72 back to the caller.

return evaluation

where the evaluation takes places first, and the return thereafter.

1 Like