一个数的阶乘是所有从 1 到该数的整数的乘积。
例如,6 的阶乘是 1*2*3*4*5*6 = 720
。负数的阶乘未定义,零的阶乘是一,0! = 1
。
使用循环计算一个数的阶乘
# Python program to find the factorial of a number provided by the user.
# change the value for a different result
num = 7
# To take input from the user
#num = int(input("Enter a number: "))
factorial = 1
# check if the number is negative, positive or zero
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
输出
The factorial of 7 is 5040
注意:要测试不同数字的程序,请更改 num
的值。
这里,要计算阶乘的数字存储在 num
中,我们使用 if...elif...else
语句检查数字是负数、零还是正数。如果数字是正数,我们使用 for
循环和 range() 函数计算阶乘。
迭代 | 阶乘*i(返回值) |
i = 1 | 1 * 1 = 1 |
i = 2 | 1 * 2 = 2 |
i = 3 | 2 * 3 = 6 |
i = 4 | 6 * 4 = 24 |
i = 5 | 24 * 5 = 120 |
i = 6 | 120 * 6 = 720 |
i = 7 | 720 * 7 = 5040 |
使用递归计算一个数的阶乘
# Python program to find the factorial of a number provided by the user
# using recursion
def factorial(x):
"""This is a recursive function
to find the factorial of an integer"""
if x == 1 or x == 0:
return 1
else:
# recursive call to the function
return (x * factorial(x-1))
# change the value for a different result
num = 7
# to take input from the user
# num = int(input("Enter a number: "))
# call the factorial function
result = factorial(num)
print("The factorial of", num, "is", result)
在上面的示例中,factorial()
是一个递归函数,它会调用自身。这里,函数将通过递减 x 的值来递归调用自身。
另请阅读