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 of 5 is 120
How it works
- Factorials are only defined for whole numbers 0 and above, so a negative number gets a message instead.
factorialstarts at 1, because multiplying by 1 leaves a number unchanged.- The loop multiplies it by every number from 1 to
numin turn. - For
num = 0the loop never runs, so the answer stays 1, which matches the rule that 0! = 1.
Other ways to write it
Using recursion
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()
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.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises