Last Updated : 14 Aug, 2025
Recursion is a programming technique where a function calls itself either directly or indirectly to solve a problem by breaking it into smaller, simpler subproblems.
In Python, recursion is especially useful for problems that can be divided into identical smaller tasks, such as mathematical calculations, tree traversals or divide-and-conquer algorithms.
Working of RecursionA recursive function is just like any other Python function except that it calls itself in its body. Let's see basic structure of recursive function:
def recursive_function(parameters):
if base_case_condition:
return base_result
else:
return recursive_function(modified_parameters)
Recursive function contains two key parts:
Let's understand recursion better with the help of some examples.
Example 1: Factorial CalculationThis code defines a recursive function to calculate factorial of a number, where function repeatedly calls itself with smaller values until it reaches the base case.
Python
def factorial(n):
if n == 0: # Base case
return 1
else: # Recursive case
return n * factorial(n - 1)
print(factorial(5))
Explanation:
This code defines a recursive function to calculate nth Fibonacci number, where each number is the sum of the two preceding ones, starting from 0 and 1.
Python
def fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)
print(fibonacci(10))
Explanation:
Recursion can be broadly classified into two types: tail recursion and non-tail recursion. The main difference between them is related to what happens after recursive call.
This code compares tail recursion and non-tail recursion using two versions of factorial function one with an accumulator (tail-recursive) and one with multiplication after recursive call (non-tail-recursive).
Python
def tail_fact(n, acc=1):
# Base case
if n == 0:
return acc
# Tail recursive call with an accumulator
else:
return tail_fact(n-1, acc * n)
def nontail_fact(n):
# Base case
if n == 1:
return 1
# Non-tail recursive call because the multiplication happens after the call
else:
return n * nontail_fact(n-1)
# Example usage
print(tail_fact(5))
print(nontail_fact(5))
Explanation:
It is often more intuitive and easier to implement when the problem is naturally recursive, like tree traversals. It can lead to solutions that are easier to understand compared to iterative ones.
Iteration:Iteration involves loops (for, while) to repeat the execution of a block of code. It is generally more memory-efficient as it does not involve multiple stack frames like recursion.
When to Avoid RecursionRetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4