# 递归函数
def my_jiecheng(n):
if n < 0:
return r"负数没有阶乘"
elif n == 0 or n == 1:
return 1
else:
sum = n*my_jiecheng(n-1)
# i=2
# while i<=n:
# sum = i*my_jiecheng(i-1)
# i=i+1
return sum
# 递归代码简单,但是调用函数性能不好,使用for循环实现也行
def my_factorial_2(n):
sum = 1
if n < 0:
return r'负数没有阶乘'
elif n == 0 or n==1 :
return 1
else:
for i in range(1,n+1):
sum = sum*i
return sum
if __name__=="__main__":
print(my_jiecheng(6))
python 递归,或者for循环 实现阶乘
于 2020-07-15 17:44:15 首次发布