Python 函数实现任意数的阶乘计算
以下是使用 Python 编写的函数,用于计算任意输入数 n 的阶乘:
def factorial(n):
result = 1
for i in range(1, n+1):
result *= i
return result
使用示例:
print(factorial(5)) # 输出:120
print(factorial(10)) # 输出:3628800
注意事项:
- 对于输入为 0 的情况,函数返回 1,因为 0 的阶乘定义为 1。
- 对于输入为负数的情况,函数抛出 ValueError 异常,因为负数没有阶乘定义。
原文地址: https://www.cveoy.top/t/topic/oCIx 著作权归作者所有。请勿转载和采集!