Python Recursive Function Definition and usage example, python recursive function example
This example describes the definition and usage of Python recursive functions. We will share this with you for your reference. The details are as follows:
Recursive functions
You can call other functions within a function. If a function calls itself internally, this function is a recursive function.
For example, let's calculate the factorial n! = 1*2*3 *... * n, represented by the function fact (n), we can see that:
Fact (n) = n! = 1*2*3 *... * (n-1) * n = (n-1 )! * N = fact (n-1) * n
Therefore, fact (n) can be represented as n * fact (n-1). Special processing is required only when n = 1.
Therefore, fact (n) is written recursively as follows:
def fact(n):if n==1: return 1return n * fact(n - 1)
The above is a recursive function. Try:
>>> fact(1)1>>> fact(5)120>>> fact(100)93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000L
If we calculate fact (5), we can see the calculation process as follows according to the function definition:
===> 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
Recursive functions have simple definitions and clear logic. Theoretically, all recursive functions can be written as loops, but the loop logic is not as clear as recursion.
Avoid stack overflow when using recursive functions. In a computer, function calls are implemented through the stack data structure. Every time a function call is initiated, a stack frame is added to the stack, the stack will be reduced by a layer of stack frames. Because the stack size is not infinite, too many recursive calls may cause stack overflow. You can try to calculate fact (10000 ).
def digui(n): sum = 0 if n<=0: return 1 else: return n*digui(n-1)print(digui(5))