Python exercise question 021: Recursive Method for factorial, python021
[Python exercise question 021]Use the recursive method to calculate 5 !.
----------------------------------------------
First, you have to figure it out: 5! It refers to the "5 factorial", that is, 5! = 1*2*3*4*5.
Then, it is said that "recursion" is a function called for itself. It's strange to hear that the Code is as follows:
Def f (x): if x = 0: return 0 elif x = 1: return 1 else: return (x * f (x-1) print (f (5 ))
It indicates that if x = 5, the value of 5 * f (4) is returned. To know the value, you must first calculate the value of f (4. F (x), f (4) = 4 * f (3), so f (5) = 5*4 * f (3 ). Push to f (5) = 5*4*3*2 * f (1 ). The f (x) function says that when x = 1, the return value is 1. Therefore, f (5) = 5*4*3*2*1 = 120. Therefore, the output result is as follows:
120
It sounds very troublesome and hard to understand. What if recursive functions are not required? The most basic code can be written as follows:
F = 1for I in range (1, 6): f = f * iprint (f)
The same result is 120.
The Code of recursive functions is concise and the logic is clear. For this question ...... Yes?
++
Source: getting started with programming languages: 100 typical examples [Python]