Python Practice › Basic Programs › Program 23
Factorial of a number
Write a Python program to find the factorial of a number. n! = 1 × 2 × … × n, and 0! = 1.
Input
n = 6
Output
6! = 720
Approach
- Start with 1 and multiply by every number from 2 to n.
Solution 1: loop
n = 6factorial = 1for i in range(2, n + 1): factorial *= iprint(f"{n}! = {factorial}")Output
6! = 720
Line by line
Line 2
Start at 1, the identity for multiplication (and the value of 0!).
Line 3
range(2, n + 1) gives 2, 3, 4, 5, 6; the end value is excluded, so add 1.
Line 4
*= multiplies the running result by each number.
Solution 2: math.factorial
import mathprint(math.factorial(6), math.factorial(0))Output
720 1
Line by line
Line 2
The standard library already has an efficient factorial function.
Learn the concept
New to this topic? Read the lesson, then come back.