原文: https://www.programiz.com/python-programming/examples/factorial-recursion
要理解此示例,您应该了解以下 Python 编程主题:
一个数字的阶乘是从 1 到该数字的所有整数的乘积。
例如,阶乘 6 是1*2*3*4*5*6 = 720。 没有定义负数的阶乘,零阶的阶乘是 1,0! = 1。
# Factorial of a number using recursion
def recur_factorial(n):
if n == 1:
return n
else:
return n*recur_factorial(n-1)
num = 7
# check if the number is negative
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
print("The factorial of", num, "is", recur_factorial(num)) 输出
The factorial of 7 is 5040 注意:要查找另一个数字的阶乘,请更改num的值。
在此,编号存储在num中。 该数字将传递给recur_factorial()函数以计算该数字的阶乘。