- Home
- /
- Python Recursion
Python Tutorial
Introduction
Python Data Types & Oper...
Python Strings
Python Lists
Python Tuples
Python Sets
Python Dictionaries
Conditional Statements
Python Loops
Python Functions
Python Modules
Python OOPS
Advanced Topics
File Handling
- Home
- /
- Python Recursion
Python Recursion
In Python, a function can call itself. This technique is called recursion. It allows a function to solve a problem by breaking it down into smaller versions of the same problem.
Think of recursion like looking into a mirror that reflects another mirror—each layer keeps repeating the same pattern until a stopping point.
When to use recursion?
Recursion is useful for problems like:
Calculating factorials
Finding Fibonacci numbers
Traversing nested structures (like folders or trees)
Example: Calculating Factorial Recursively
Let’s write a custom factorial function using recursion:
def compute_factorial(n):
if n <= 1:
return 1
return n * compute_factorial(n - 1)
number = 6
print("Number:", number)
print("Factorial:", compute_factorial(number))
Output:
Number: 6
Factorial: 720
How it works:
The function keeps calling itself with a smaller number.
When it reaches
n <= 1
, it returns 1.Then all the previous calls multiply the numbers step-by-step until the original number’s factorial is formed.
Summary
Recursion lets you solve problems by having a function call itself. However, it must always include a base case (a stopping condition) or it could run infinitely.