Editor

Python Program to Find the Factorial of a Number

Beginner · Numbers · CBSE class 11 practical list · CBSE class 12 practical list

The factorial of a whole number n, written n!, is the product of all whole numbers from 1 to n. For example, 5! = 1 x 2 x 3 x 4 x 5 = 120, and by definition 0! = 1. This program works out the factorial with a loop.

Program

factorial.py
num = 5 # or: num = int(input("Enter a number: "))
if num < 0:
print("Factorial is not defined for negative numbers")
else:
factorial = 1
for i in range(1, num + 1):
factorial *= i # multiply by 1, then 2, then 3, ...
print("Factorial of", num, "is", factorial)
Output
Factorial of 5 is 120

How it works

  1. Factorials are only defined for whole numbers 0 and above, so a negative number gets a message instead.
  2. factorial starts at 1, because multiplying by 1 leaves a number unchanged.
  3. The loop multiplies it by every number from 1 to num in turn.
  4. For num = 0 the loop never runs, so the answer stays 1, which matches the rule that 0! = 1.

Other ways to write it

Using recursion

Using recursion
def factorial(n):
if n == 0: # base case: 0! is 1
return 1
return n * factorial(n - 1)
for n in [0, 1, 5, 10]:
print(f"{n}! =", factorial(n))
Output
0! = 1
1! = 1
5! = 120
10! = 3628800

The function calls itself with a smaller number until it reaches 0; Python stops recursion after about 1000 calls, so the loop is safer for big numbers.

Using math.factorial()

Using math.factorial()
import math
num = 20
print("Factorial of", num, "is", math.factorial(num))
Output
Factorial of 20 is 2432902008176640000

The math module has a ready-made factorial, and because Python integers have no size limit, even large factorials print exactly.

Try it yourself

Change the program to print every factorial from 1! to 10!, each on its own line.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises