用递归求5!的阶乘
一般计算:
1 n = int(input("输入数:")) 2 factorial = 1 3 for i in range(1,n+1): 4 factorial *= i 5 print(factorial) 6 print("{}!的阶乘为{}".format(n,factorial))
执行结果:
输入数:5 1 2 6 24 120 5!的阶乘为120
递归计算:
1 def factorial(n): 2 if n == 1: 3 return 1 4 if n == 2: 5 return 2 6 else: 7 return factorial(n-1)*n 8 if __name_ 9 print(factorial(5))