What "really" return
does in Python, especially in recursive functions. Ex. Factorial:
def fatorial(n):
if n==1:
return n
return fatorial(n-1) * n
What "really" return
does in Python, especially in recursive functions. Ex. Factorial:
def fatorial(n):
if n==1:
return n
return fatorial(n-1) * n
As in any mainstream language, return
terminates execution of the current function, returning exactly to the point where it was called.
Eventually it may return a value as a result of the function, ie where the function was called will have the return value used in the expression built there.
There is nothing special about return
when it is used in recursive functions. The operation is exactly the same. In a recursive function the calls accumulate and the returns will occur after returning always to the same point, but in different states. Obviously at some point you need to stop making recursive calls, otherwise you will have infinite recursion and pop the stack.
As it is not a special case, if there is a large number of calls, and each call keeps its own state (values of local variables), it will fill stack of the application and may give the stack overflow .
It returns the value of the function. In the specific case of recursive functions, it, in addition to returning the value (which can also be a null value None
), will also return the control flow to the calling function.