Python programs · Numbers
Python program to find the factorial of a number
The factorial of n, written n!, is 1 × 2 × 3 × … × n. It counts the ways to arrange n different things in a row.
Approach
- Start a running product at 1.
- Multiply it by every number from 2 to n.
- Print the final product.
The program
n = int(input()) result = 1 for i in range(2, n + 1): result *= i print(f"{n}! = {result}")
Sample run
Input
5
Output
5! = 120
How the code works
range(2, n + 1) runs from 2 to n, because the stop value is never included. The product starts at 1, not 0, since multiplying by 0 would erase everything. By definition 0! is 1, and this loop gives that answer too: the loop body never runs, so the result stays 1. Python integers grow as large as needed, so large factorials print in full.
Try changing it
- Write it with recursion:
def fact(n): return 1 if n <= 1 else n * fact(n - 1). - Use
math.factorial(n)and compare the two answers.
Common mistakes
- Starting the product at 0, which makes every answer 0.
- Using
range(n), which starts at 0 and stops at n - 1.