Home  >  Article  >  Backend Development  >  How to find factorial in python

How to find factorial in python

PHPz
PHPzOriginal
2020-09-25 15:56:30101989browse

Python factorial method: 1. Use an ordinary for loop; 2. Use the [reduce()] function, the code is [num = reduce(lambda x,y:x*y,range(1,7 ))]; 3. Use the [factorial()] function; 4. Call the method recursively.

How to find factorial in python

Related learning recommendations: python tutorial

Python factorial method:

The first method : Ordinary for loop

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)

The second type: reduce() function

#从functools中调用reduce()函数
from functools import reduce
#使用lambda,匿名函数,迭代
num = reduce(lambda x,y:x*y,range(1,7))
print(num)

The third type: factorial() function

import math
value = math.factorial(6)
print(value)

The fourth type: recursive call

def num(n):
    if n == 0:
        return 1
    else:
        return n * num(n - 1)
print(num(6)

The above is the detailed content of How to find factorial in python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn