📘 Lesson · Lesson 75
Factorial Program
Factorial Program in Python (Loop and Recursion)
The factorial of n (written n!) is the product of all numbers from 1 to n. Example: 5! = 120.
Python Program
Python
# Using a loop
n = 5
f = 1
for i in range(1, n + 1):
f *= i
print("Factorial:", f)
# Using recursion
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
print("Recursive:", factorial(5))Expected Output
Factorial: 120
Recursive: 120
How it Works
- Loop: multiply f by each number from 1 to n.
- Recursion: n! = n × (n-1)!, with base case 0! = 1.
Summary
- The factorial of n (written n!) is the product of all numbers from 1 to n. Example: 5! = 120.
💻 Live Code Editor
This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.