Python Program to Find the Factorial of a Number
Beginner Numbers
Finds the factorial of a number, the product of every whole number from 1 to n, with a for loop.
The factorial of a whole number n, written n!, is the product of every whole number from 1 to n: 5! = 1 ร 2 ร 3 ร 4 ร 5 = 120. It counts the ways to put n things in order, so 5 books can stand on a shelf in 120 different orders. By definition, 0! is 1.
Program
def factorial(n):
"""The factorial of n: 1 * 2 * 3 * ... * n."""
result = 1
for number in range(1, n + 1):
result *= number
return result
print("5! =", factorial(5))
print("0! =", factorial(0))
Open in the editor Download factorial.py
Output
5! = 120
0! = 1
How it works
Step through the program line by line: each step below shows up as its line runs.
-
resultstarts at 1, not 0, as multiplying anything by 0 would give 0. - The loop multiplies
resultby every number from 1 ton.range(1, n + 1)stops beforen + 1, sonitself is included.result *= numberis short forresult = result * number. - After the loop,
resultholds the product, and the function returns it. - The program works out 5! and 0!. For 0,
range(1, 1)is empty, so the loop never runs and the function returns the 1 it started with, which is the right answer.
For 5, result goes like this:
| number | result |
|---|---|
| 1 | 1 ร 1 = 1 |
| 2 | 1 ร 2 = 2 |
| 3 | 2 ร 3 = 6 |
| 4 | 6 ร 4 = 24 |
| 5 | 24 ร 5 = 120 |
Other ways to write it
With recursion
n! is n ร (n โ 1)!, so the function can call itself with a smaller number until it reaches 1
(recursion). Python allows about 1000 calls inside each other, so a large n, such as 5000, fails
with a RecursionError, which the loop never does.
def factorial(n):
if n <= 1:
return 1
return n * factorial(n - 1)
print(factorial(6))With math.factorial()
The standard library has it built in, written in C, so it's faster. It raises a ValueError for a negative number.
import math print(math.factorial(10))
Try it yourself
- Work out 10! and 20!. 20! is 2432902008176640000: Python's whole numbers grow as big as they need to.
- Print 1! to 10! with a loop, one per line.
- For a negative
n, the function returns 1, which is wrong. Make it raise aValueErrorinstead (errors and exceptions). - Count the zeros at the end of 25!: there are 6.