Inside a function, you can call other functions. If a function calls itself internally, this function is
Recursive Functions。
For example, let's calculate factorial n! = 1 x 2 x 3 x ... x n, denoted by the function fact (n), you can see:
Fact (n) = n! = 1 x 2 x 3 x ... x (n-1) x n = (n-1)! X n = fact (n-1) x n
So, fact (n) can be represented as N x fact (n-1), which requires special handling only when n=1.
So, fact (n) is written in a recursive way :
def fact (n): if n==1: return 1 return n * Fact (N-1)
Above is a recursive function. You can try:
>>> fact (1) 1>>> fact (5) 120>>> fact (100) 9332621544394415268169923885626670049071596826438162146859296389521759999322991560894146397615651828625369792082722375825 1185210916864000000000000000000000000
If we calculate the fact (5), we can see the calculation process according to the function definition as follows:
===> Fact (5)
===> 5 * FACT (4)
===> 5 * (4 * FACT (3))
===> 5 * (4 * (3 * FACT (2)))
===> 5 * (4 * (3 * (2 * FACT (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 fact (1000):
>>> fact (Traceback): file "<stdin>", line 1, in <module> file "& Lt;stdin> ", line 4, in fact ... File "<stdin>", line 4, in factruntimeerror:maximum recursion depth exceeded in comparison