Inside the function we can call other functions such as:
def say (Great): return Great def Person (name): Print (Say ("Hello"), name) person (" Sandichicks ")
Print as follows:
>>> Hello Sandichicks
But if we call ourselves, this function is a recursive function
For example, let's calculate factorial n! = 1 x 2 x 3 x ... x n (for example, the factorial of 5:5*4*3*2*1) is indicated by the function fact (n), which shows:
Fact (n) = n! = 1x 2 x 3 x ..... x (n-1) x n = (n-1)! X n = fact (n-1) * n
So, fact (n) can represent n * Fact (n-1), and only n = 1 o'clock requires special handling. (otherwise 1*fact (1-1) =0 no meaning)
So, fact (n) is written in a recursive way:
def fact (N): if n = =1 :return 1 return N * Fact (N-1)
The above is a recursive function, we write it a function to facilitate our presentation of the results
Detail = input ("Factorial calculator: 99 reference Calculator Press any key to continue \ n")defFace (n):ifn = = 1: return1returnn * Face (n-1) whileTrue:num= Int (Input ("Enter the number of factorial you want to find:")) Print("the factorial result is:", Face (num))Print("---------------------")
So we can demonstrate the factorial calculator program we wrote!
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.
Python: recursive function