Introduction
Recursion is a fundamental concept in computer science where a function calls itself to solve a problem.
It’s especially useful for problems that can be broken down into smaller, similar sub-problems like
calculating factorials, traversing trees, or solving puzzles.
Objective
In this tutorial, you’ll learn how to implement a recursive function in Python through a simple and classic example — calculating the factorial of a number.
Python Code: Recursive Function to Calculate Factorial
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
# Example usage
number = 5
print(f"The factorial of {number} is: {factorial(number)}")
Explanation
Here’s a breakdown of the program structure:
- Base Case: If
n
is 0 or 1, the function returns 1. This stops the recursion from continuing indefinitely. - Recursive Case: The function calls itself with
n - 1
until it reaches the base case. Each call returnsn * factorial(n - 1)
. - The result is printed using
print()
.
How to Run the Program
- Copy the code into a file and save it as
factorial.py
. - Open your terminal or command prompt.
- Navigate to the folder where the file is saved.
- Run the program using the command:
python factorial.py
- You’ll see the output:
The factorial of 5 is: 120