What is the purpose of the return statement?

Hitesh Kumar picture Hitesh Kumar · Aug 20, 2011 · Viewed 633.3k times · Source

What is the simple basic explanation of what the return statement is, how to use it in Python?

And what is the difference between it and the print statement?

Answer

Nathan Hughes picture Nathan Hughes · Aug 20, 2011

The print() function writes, i.e., "prints", a string in the console. The return statement causes your function to exit and hand back a value to its caller. The point of functions in general is to take in inputs and return something. The return statement is used when a function is ready to return a value to its caller.

For example, here's a function utilizing both print() and return:

def foo():
    print("hello from inside of foo")
    return 1

Now you can run code that calls foo, like so:

if __name__ == '__main__':
    print("going to call foo")
    x = foo()
    print("called foo")
    print("foo returned " + str(x))

If you run this as a script (e.g. a .py file) as opposed to in the Python interpreter, you will get the following output:

going to call foo
hello from inside foo
called foo   
foo returned 1

I hope this makes it clearer. The interpreter writes return values to the console so I can see why somebody could be confused.

Here's another example from the interpreter that demonstrates that:

>>> def foo():
...     print("hello from within foo")
...     return 1
...
>>> foo()
hello from within foo
1
>>> def bar():
...   return 10 * foo()
...
>>> bar()
hello from within foo
10

You can see that when foo() is called from bar(), 1 isn't written to the console. Instead it is used to calculate the value returned from bar().

print() is a function that causes a side effect (it writes a string in the console), but execution resumes with the next statement. return causes the function to stop executing and hand a value back to whatever called it.