Problem 7: Factorial

Python Developer | Audio Editor | Technical Writer | OSS Contributor | Tag Moderator @ @ThePracticalDEV | Valorant TonyPoppins #881488
Hey everyone! 👋
Today, we're tackling a classic mathematical problem: Calculating the Factorial.
The Problem
The goal is to write a function that calculates the factorial of a number.
The factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n.
Formula: n! = n × (n-1) × (n-2) × ... × 1
Special Case: 0! = 1
Example:
factorial(5)should return120(because5 × 4 × 3 × 2 × 1 = 120)factorial(0)should return1
The Solution
Here is the Python implementation using a loop:
def factorial(n):
"""
Calculates the factorial of a number using a loop.
"""
# Base case: 0! and 1! are both 1
if n == 0 or n == 1:
return 1
else:
result = 1
# Loop from 2 up to n
for i in range(2, n + 1):
result *= i
return result
# Test cases
print(factorial(5))
# Output: 120
print(factorial(0))
# Output: 1
print(factorial(7))
# Output: 5040
Code Breakdown
Let's walk through the code line by line:
def factorial(n):- Defines a function named
factorialthat takes one parametern(the number to calculate the factorial for).
- Defines a function named
if n == 0 or n == 1: return 1Base case: If
nis0or1, we return1immediately.This is because
0!is defined as1, and1!is obviously1.
else: result = 1If
nis greater than1, we initialize a variableresultto1.1is the multiplicative identity (multiplying by 1 doesn't change the value), making it a safe starting point.
for i in range(2, n + 1):We start a loop that iterates from
2up ton.range(2, n + 1)generates numbers starting from2and stopping beforen + 1, which means it includesn.
result *= iIn each iteration, we multiply the current
resultby the loop variablei.This accumulates the product (
1 * 2 * 3 * ... * n).
return result- After the loop finishes, we return the final computed factorial value.
Example Walkthrough with factorial(5)
Let's trace what happens when we call factorial(5):
Check: Is
5equal to0or1? No.Initialize:
resultstarts at1.Loop:
iwill take values2,3,4,5.i = 2:
result= 1 * 2 = 2i = 3:
result= 2 * 3 = 6i = 4:
result= 6 * 4 = 24i = 5:
result= 24 * 5 = 120
Return: The loop ends, and the function returns
120.
Happy coding! 💻






