+ 1
How is function of return work in python?
2 Answers
0
For simplicity, let us assume a few things. Only one value is returned at a time, functions are simple and call no functions, and more as we go.
Now, a simple function can be seen as a stack. This stack executes from top, with return at the bottom. Each item on the stack is a statement. So you evaluate one at a time merrily until you hit the return statement.
At the return statement, that is, at the bottom of the stack, you simply leave the value to be returned. Python knows better than end of current function is the end of the world. So it goes on to execute the caller's statement that called your function in the first place. Since it was a function call, Python knows that a new stack was built for the function and looks at it's return value which we assume is at the place where return statement was, and provides the caller with that value.
With the result, the caller goes on to next instruction.
Since this is a learners discussion, I have taken the liberty of explaining how a general function returns. That is, any stack based language will follow these steps to implement return statement.
Then it goes without mentioning that Python specific details have been omitted.
0
The return method creates the value that a def function (or something similar) outputs. You can then assign the function to a variable to store the returned value.
def double(x):
return x * 2
six = double(3)
# The value stored in six is now 6.



