python函数阶乘
时间: 2023-11-30 19:01:57 浏览: 70
Python之调用函数共3页.pdf.zip
Python中可以使用循环或者递归的方式来实现阶乘函数。下面是两种实现方式:
1.循环实现阶乘函数:
def factorial(num):
if num < 0:
return "阶乘未定义负数"
elif num == 0:
return 1
else:
result = 1
for i in range(1, num+1):
result *= i
return result
print(factorial(5)) # 输出120
2.递归实现阶乘函数:
def factorial(num):
if num < 0:
return "阶乘未定义负数"
elif num == 0:
return 1
else:
return num * factorial(num-1)
print(factorial(5)) # 输出120
阅读全文