Recursion in Python (original) (raw)

Last Updated : 19 May, 2026

Recursion is a programming technique where a function calls itself either directly or indirectly to solve a problem. It is commonly used for:

Working of Recursion

A recursive function 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)

1

Recursion in Python

Recursive function contains two key parts:

Examples

**Example 1: This 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:

**Example 2: 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:

Types of Recursion

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.

**Example: 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): if n == 0: return acc else: return tail_fact(n-1, acc * n)

def nontail_fact(n): if n == 0: return 1 else: return n * nontail_fact(n-1)

print(tail_fact(5))
print(nontail_fact(5))

`

**Explanation:

When to Avoid Recursion

Recursion vs Iteration

Recursion and iteration are two common techniques used to repeat tasks in programming below table highlights the key differences between them:

Feature Recursion Iteration
Method A function calls itself to repeat the task Uses loops (for, while) to repeat steps
Memory Use Uses more memory due to function calls Uses less memory
Performance Usually slower because of function call overhead Generally faster as it avoids repeated function calls
Best Used For Problems like tree traversal or divide-and-conquer Repeating steps in a sequence
Risk May cause stack overflow if recursion is too deep No stack overflow risk