Home>Article>Backend Development> How to find factorial in python
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.
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!