python编写函数求任意输入数n的阶乘。
以下是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/g9Iz 著作权归作者所有。请勿转载和采集!