一、初级的for循环计算阶乘:
1 def factorial(n): 2 result = n 3 for i in range(1, n): 4 result *= i 5 return result 6 7 8 temp = int(input('请输入一个正整数:')) 9 res = factorial(temp) 10 print('%d的阶乘:%d' % (temp, res))
二、用递归函数简化的阶乘计算:
1 def factorial1(n): 2 if n == 1: 3 return 1 4 else: 5 return n * factorial1(n - 1) 6 temp = int(input('请输入一个正整数:')) 7 res = factorial1(temp) 8 print('%d的阶乘:%d' % (temp, res))
三、用functools.reduce结合lambda计算阶乘:
1 import functools 2 temp = int(input('请输入一个正整数:')) 3 res = functools.reduce(lambda x, y: x * y, range(1,temp + 1)) 4 # x取x*y的值,y取range(1,temp+1)的值,最后效果(((1*2)*3)...*temp) 5 print('%d的阶乘:%d' % (temp, res))