本文摘自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操作sqlite数据库与文件操作的实例详解
Python配置mysql的教程(必看)
Python md5与sha1加密算法的详细介绍
Python如何安装rabbitmq
linux环境使用pdb调试Python的方法
Python基于flask上传文件的代码示例
介绍Python的函数装饰器
Python爬虫是什么?为什么把Python叫做爬虫?
解决Python删除文件的权限错误问题
回味Python基本数据类型
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » python如何求阶乘