I'm learning Python and keep seeing return at the end of functions. What does it mean in everyday terms, and how is it different from printing something?
What does it actually mean when a function returns a value?
Answers
Think of asking someone to work out a total for you. Returning is them handing you the answer, so you can write it down or use it in another calculation.
A function does the same kind of handoff to the code that called it. If double(n) calculates n times 2 and returns it, then x = double(5) puts 10 in x. The calling code can use that 10 later.
Reply to this answer
Printing is more like putting the answer on a display. Returning gives the answer back to the calling code. Seeing 10 on the screen doesn't automatically put 10 in a variable you can use later.
In Python, a function that only prints 10 and doesn't explicitly return anything will return None. So x = that_function() can show 10 on screen, but x will be None.
Reply to this answer
Return also ends the function at that point. If a function has return n, it hands back the current value of n and stops running that call. Any statements after that return in the same path won't run.
p.527~coppergizmo:
In Python, a bare return also ends the function, but its return value is None.
Reply to this answer
One useful way to look at it is that a function call can be part of a bigger expression. If double(5) returns 10, then double(5) + 3 evaluates to 13. You don't have to save the result in a variable first.
Reply to this answer
Add your answer
Answers are reviewed before publication.
_v18~jaspello.4:
So the return value is what takes the place of double(5) in that assignment?
Mavdrix-8s:
Yes. The call runs the function and produces 10, which the assignment then stores in x.