Home > Backend Development > Python Tutorial > How to find factorial in python

How to find factorial in python

PHPz
Release: 2020-09-27 13:06:28
Original
102276 people have browsed it

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(&#39;负数没有阶乘!&#39;)
elif a == 0:
    print(&#39;0的阶乘为1!&#39;)
else :
    for i in range(1,a + 1):
        num *= i
    print(num)
Copy after login

The second type: reduce() function

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

The third type: factorial() function

import math
value = math.factorial(6)
print(value)
Copy after login

The fourth type: recursive call

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

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template