function recursion In fact there is no specific syntax, can be understood as a thought, I like to call him recursive thinking
-------------------------------------------------------------------------------------------------------
Simple can be understood as:
Inside a function, other functions can be called, or he can invoke itself, which is a recursive function
Example (1):
def func (n): n+=1 if n>=5: return ' End ' return func (N) r=func (1) print (R)
This is a simple recursive idea:
function func Each operation is increased by +1, if to 5 return an ' end ', and return to continue the operation, the entire function is to call itself
Example (2):
Def d (): return ' 123 ' Def c (): r=d () return rdef B (): r=c () return rdef A (): r=b () print ( R) A ()
Function A calls b;b C; The return value of C calls D;d is 123, and then returns to a, which is also a recursive thought
Example (3):
Here is a recursive function, you can try
>>> func (1)
1
>>> func (5)
120
def func (n): if n==1: return 1 return n * func (n-1) R=func (5) print (R)
If we calculate func (5), you can see the calculation process as follows from the function definition:
===> func (5)
===> 5 * func (4)
===> 5 * (4 * func (3))
===> 5 * (4 * (3 * func (2)))
===> 5 * (4 * (3 * (2 * func (1)))
===> 5 * (4 * (3 * (2 * 1)))
===> 5 * (4 * (3 * 2))
===> 5 * (4 * 6)
===> 5 * 24
===> 120
The advantage of recursive functions is that they are simple in definition and clear in logic. In theory, all recursive functions can be written in a circular way, but the logic of the loop is not as clear as recursion.
The use of recursive functions requires careful prevention of stack overflow. In the computer, the function call is implemented through a stack (stack) of this data structure, each time into a function call, the stack will add a stack of frames, whenever the function returns, the stack will be reduced by a stack of frames. Because the size of the stack is not infinite, there are too many recursive calls that can cause the stack to overflow. You can try the calculation of func (10000).
Example (4):
Attach another recursive usage
def Digui (n): sum = 0 if n<=0: return 1 else: return N*digui (n-1) Print (Digui (5))
Python Programming: function recursion