Python
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.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

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

error

Enjoy this blog? Please spread the word :)