Python Recursive Factorial Function
To calculate the factorial of n using a recursive method, you can define a recursive function that checks if n is 1, and if so, returns 1, otherwise returns n multiplied by the factorial of n-1 recursively calling the function.
Here is an example code that uses recursion to calculate the factorial of n.
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
# 测试
num = int(input("请输入一个正整数: "))
print(num, "的阶乘为", factorial(num))
In the code above, we first define a function called factorial that takes a parameter n to calculate the factorial of n. In the function, we use a conditional statement – if n is 1, we return 1; otherwise we return n multiplied by calling itself with n-1 as the input for the factorial.
In the testing section, we use the input function to retrieve the user’s input number, then we invoke the factorial function and print the result.