Recursion in Python (original) (raw)

Last Updated : 20 Mar, 2025

Recursion involves a function calling itself directly or indirectly to solve a problem by breaking it down into simpler and more manageable parts. In Python, recursion is widely used for tasks that can be divided into identical subtasks.

In Python, a recursive function is defined like any other function, but it includes a call to itself. The syntax and structure of a recursive function follow the typical function definition in Python, with the addition of one or more conditions that lead to the function calling itself.

Basic Example of Recursion:

Python `

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

print(factorial(5))

`

**Explanation: The factorial of a number n (denoted as n!) is the product of all positive integers less than or equal to n. The recursive approach involves the function calling itself with a decremented value of n until it reaches the base case of 1.

Let’s understand recursion in python deeply:

Table of Content

Basic Structure of Recursive Function

def recursive_function(parameters):

if base_case_condition:

return base_result

else:

return recursive_function(modified_parameters)

img

Base Case and Recursive Case

**Example:

Python `

def fibonacci(n): # Base cases if n == 0: return 0 elif n == 1: return 1 # Recursive case else: return fibonacci(n-1) + fibonacci(n-2)

Example usage

print(fibonacci(10))

`

**Explanation:

Types of Recursion in Python

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 the recursive call.

Here is a Python example that demonstrates both tail recursion and non-tail recursion:

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))

`

Recursion vs Iteration

Recursion:

Iteration:

Advantages of using recursion

Disadvantages of using recursion