2022年 11月 5日

python中求阶乘的代码_python如何求阶乘

python阶乘的方法:1、使用普通的for循环;2、使用【reduce()】函数,代码为【num = reduce(lambda x,y:x*y,range(1,7))】;3、使用【factorial()】函数;4、递归调用方法。

python阶乘的方法:

第一种:普通的for循环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()函数#从functools中调用reduce()函数

from functools import reduce

#使用lambda,匿名函数,迭代

num = reduce(lambda x,y:x*y,range(1,7))

print(num)

第三种:factorial()函数import math

value = math.factorial(6)

print(value)

第四种:递归调用def num(n):

if n == 0:

return 1

else:

return n * num(n – 1)

print(num(6)