Python program: Factorial of a number
n! = 1 × 2 × … × n. Calculate it with a loop, recursion and the math module.
The code
import math def factorial_loop(n): result = 1 for i in range(2, n + 1): result *= i return result def factorial_rec(n): return 1 if n <= 1 else n * factorial_rec(n - 1) for n in [0, 1, 5, 10]: print(n, factorial_loop(n), factorial_rec(n), math.factorial(n))
Output
0 1 1 1 1 1 1 1 5 120 120 120 10 3628800 3628800 3628800
How it works
The loop multiplies an accumulator; the recursive version uses 0! = 1! = 1 as its base case. Python integers never overflow, so even 100! is exact.
Python features used
Learn the ideas behind it in the free lesson More Functions.