一个数的阶乘是从 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()
函数以计算该数字的阶乘。
另请阅读