How to Implement Recursion in Python

 

 

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 returns n * factorial(n - 1).
  • The result is printed using print().

How to Run the Program

  1. Copy the code into a file and save it as factorial.py.
  2. Open your terminal or command prompt.
  3. Navigate to the folder where the file is saved.
  4. Run the program using the command: python factorial.py
  5. You’ll see the output: The factorial of 5 is: 120
© 2025 Learn Programming. All rights reserved.

 

Leave a Reply

Your email address will not be published. Required fields are marked *