本文摘自php中文网,作者PHPzhong,侵删。
python阶乘的方法:1、使用普通的for循环;2、使用【reduce()】函数,代码为【num = reduce(lambda x,y:x*y,range(1,7))】;3、使用【factorial()】函数;4、递归调用方法。

相关学习推荐:python教程
python阶乘的方法:
第一种:普通的for循环
1 2 3 4 5 6 7 8 9 10 | a = int(input( 'please inputer a integer:' ))
num = 1
if a < 0:
print ( '负数没有阶乘!' )
elif a == 0:
print ( '0的阶乘为1!' )
else :
for i in range(1,a + 1):
num *= i
print (num)
|
第二种:reduce()函数
1 2 3 4 5 | #从functools中调用reduce()函数
from functools import reduce
#使用lambda,匿名函数,迭代
num = reduce(lambda x,y:x*y,range(1,7))
print (num)
|
第三种:factorial()函数
1 2 3 | import math
value = math.factorial(6)
print (value)
|
第四种:递归调用
1 2 3 4 5 6 | def num(n):
if n == 0:
return 1
else :
return n * num(n - 1)
print(num(6)
|
以上就是python如何求阶乘的详细内容,更多文章请关注木庄网络博客!!
相关阅读 >>
Python + selenium自动化环境搭建的完整步骤
Python求n的阶乘
Python学会后做什么
Python如何实现可视化热力图
Python程序的运行过程如何理解?
Python实现switch/case语句的方法
Python数据挖掘需要学什么
Python实现下载文件的三种方法_Python
Python中装饰器是什么?Python中装饰器的介绍
学习Python理由是什么?
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » python如何求阶乘