第一种、利用functools工具处理
import functools <a href="https://www.gaodaima.com/tag/result" title="查看更多关于result的文章" target="_blank">result</a> = (lambda k: functools.reduce(int.__mul__, range(1, k + 1), 1))(5) print(result)
www#gaodaima.com来源gaodai#ma#com搞@@代~&码网搞代码
相关推荐:《Python教程》
第二种、普通的循环
x = 1 y = int(input("请输入要计算的数:")) for i in range(1, y + 1): x = x * i print(x)
第三种、利用递归的方式
def func(n): if n == 0 or n == 1: return 1 else: return (n * func(n - 1)) a = func(5) print(a)
以上三种方式分别采用了不同的方法,第二种是最容易理解的,第一种是最pythonic的,而第三种则是易用性最高的。第三种直接定义一个阶乘函数,随时都可以调用,从而得到不同值。
来源:搞代码网:原文地址:https://www.gaodaima.com