So I was making a diagram of the recursive function to wrap my head around recursion, and I noticed that apparently every function executes return at the end?
A return itself simply means that the call frame is popped from the call stack, the program counter is set back to state where it was before you made the call, etc. Based on your comment it looks a bit like "backtracking" but mind that - in contrast to backtracking - side effects the functions have, are not reverted/undone. For instance appending to a list, drawing a line, writing to a file, etc. are not reverted. This is the desired behavior in recursion.
Now sometimes it is useful to return a certain value. For instance:
def foo(x,y):
return x+y
here foo
does not only go back to the caller, but first evaluates x+y
and the result is returned, such that you can state z = foo(2,3)
. So here foo
is called, 2+3
is evaluated and 5
is returned and assigned to z
.
Another question, what exactly does a function return? All of parameters passed to it (assuming multiple parameters)?
In Python all functions return a value. If you specify it like:
return <expression>
the <expression>
part is evaluated and that value is returned. If you specify:
return
or no return
at all (but you reach the end of the function), None
will be returned.