本文摘自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如何安装whl文件
pytho中字典操作方法介绍(代码示例)
Python实现微信推送模板消息功能示例
Python如何计时
Python idle怎么用
如何随机生成大写字母和数字组成的字符串
Python保存数组怎么操作
Python数据分析用什么软件
怎么在Python安装bs4
Python中根据字符串导入模块module的方法介绍(附代码)
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » python如何求阶乘