Factorial is an arithmetic symbol invented by Christian Kramp (1760-1826) in 1808. It is a mathematical term. The factorial of a positive integer is the product of all positive integers less than or equal to that number, and the factorial of 0 is 1. The factorial of a natural number n is written n!.
Let’s take a look at how to use Python to calculate the factorial of n:
The first one: use the functools tool to process
import functools result = (lambda k: functools.reduce(int.__mul__, range(1, k + 1), 1))(5) print(result)```
The second one: ordinary loops
x = 1 y = int(input("请输入要计算的数:")) for i in range(1, y + 1): x = x * i print(x)
The third way: using recursion
def func(n): if n == 0 or n == 1: return 1 else: return (n * func(n - 1)) a = func(5) print(a)
Recommended: "python tutorial"
The above is the detailed content of Python finds the factorial of n. For more information, please follow other related articles on the PHP Chinese website!