The factorial of a whole number n, written n!, is the product of all whole numbers from 1 to n. For example, 5! = 1 × 2 × 3 × 4 × 5 = 120. By definition, 0! is 1.
The program
python
n = int(input("Enter a whole number: ")) if n < 0: print("Factorial is not defined for negative numbers.") else: result = 1 for i in range(1, n + 1): result *= i print(f"{n}! = {result}")
Typed in this example: 6. Press Run to type your own.
output
Enter a whole number: 6 6! = 720
How it works
resultstarts at 1, not 0. If it started at 0, every multiplication would give 0.range(1, n + 1)gives the numbers 1, 2, ..., n. The end value ofrange()is not included, so you needn + 1.result *= iis a short way to writeresult = result * i.- For
n = 0,range(1, 1)is empty, so the loop does not run and the program prints0! = 1, which is correct. - Factorials grow very fast. Python integers have no size limit, so even 50! is printed exactly.
Another way: math.factorial()
The math module has a built-in function for this:
python
import math print(math.factorial(6)) print(math.factorial(20))
output
720 2432902008176640000
math.factorial() raises a ValueError for negative numbers. The same calculation written as a function that calls itself is on the factorial using recursion page.