本文摘自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线程模块?九种方法助你了解线程模块
Python中encoding是什么意思
Python如何创建txt文件并写入
Python语言是非开源语言吗
Python list对象中嵌套元组使用sort的排序方法
Python中关于try-except用法的错误和异常处理详解
怎么在Python开发界面
Python3.6.4如何安装到树莓派3代
深入理解上篇之 Python的进程和线程
Python类怎么理解
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » python如何求阶乘