The Purpose of Return in Functions



Just a quick question regarding the purpose of 'return', particularly within a function and in general.

in 12. - Lists and Function: 6 - More Than One Argument, I defined the following function:

m = 5
n = 13
# Add add_function here!
def add_function(x,y):
    x + y

print add_function(m, n)

NOT including the 'return' functions lends to the following error:

"Oops, try again. add_function(11, 0) returned None, did you remember to return the result?"

Is this because the program interpreter cannot use the result of any operation unless you specify for the program to 'return' it? I'm not 100% sure what the 'return' adds, other than reading that 'return' allows the program to actually use the results obtained (presumably in future operations coded into the program?)


the return() function hands back a value, we usually use it at the end of our defined functions


So presumably, Python cannot do this on its own accord then? How do you know when it's appropriate to use the return function or not?


Simply put, without a return statement or function. The program is not going to return anything when you call that function. A computer isn't going to just assume you want something done. You have it tell it what to do.


well, there are two things at play here:

the python interpreter which checks if the code is valid (no syntax errors)
the exercise expecting a certain result

the code you posted above is valid syntax, but the exercise expects you to return the sum value, which is why the exercise throws you an error

lets explain based on a example:

m = 5
n = 13
# Add add_function here!
def add_function(x,y):
    return x + y

z =  add_function(m, n)
print z

Go run this code

see how 18 is printed? the function returns the sum (literally handing us something back) which we then store in a variable (z), now z contains 18 and we could do further math with z (if we want)

what you did here:

print add_function(m, n)

is printing the returned value by the function

When to use return? I am afraid there is no fixed rule, it depends upon the design of your program.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.