โญ Recursion in Python
Recursion is a programming technique where a function calls itself to solve a problem.
A recursive function breaks a large problem into smaller sub-problems and calls itself repeatedly until the problem becomes simple enough to solve directly.
๐น Definition
Recursion is a method where a function calls itself directly or indirectly.
It works by dividing a problem into smaller instances of the same problem.
๐น How Recursion Works
Every recursive function has two parts:
- Base Case
โ Condition where the recursion stops - Recursive Case
โ Function calls itself with a smaller input
โญ General Syntax of Recursion
def function_name(params):
if base_condition:
return result # base case
else:
return function_name(modified_params) # recursive call
๐ฅ Example 1: Simple Recursive Function
def countdown(n):
if n == 0: # base case
print("Stop!")
else:
print(n)
countdown(n-1) # recursive call
countdown(5)
โญ Example 2: Factorial Using Recursion
n! = n ร (nโ1)!
def factorial(n):
if n == 0 or n == 1: # base case
return 1
else:
return n * factorial(n-1) # recursive call
print(factorial(5))
Output:
120
โญ Example 3: Fibonacci Series Using Recursion
def fibonacci(n):
if n == 0:
return 0
if n == 1:
return 1
return fibonacci(n-1) + fibonacci(n-2)
print(fibonacci(6))
โญ Example 4: Sum of digits using recursion
def sum_digits(n):
if n == 0:
return 0
return (n % 10) + sum_digits(n // 10)
โญ Example 5: Reverse a string using recursion
def reverse(s):
if len(s) == 0:
return ""
return reverse(s[1:]) + s[0]
print(reverse("Python"))
๐น Types of Recursion
- Direct Recursion
Function calls itself.def f(): f() - Indirect Recursion
Function A calls B, and B calls A.def A(): B() def B(): A()
๐น How Recursion Works Internally
Recursion uses a call stack:
- Each recursive call adds a new entry to the stack
- Base case stops further calls
- Return values are passed back down the stack
โญ Advantages of Recursion
โ Code is cleaner and easier to understand
โ Problems like factorial, Fibonacci, tree traversal are easier
โ Reduces complex loops
โญ Disadvantages of Recursion
โ Slower than loops
โ More memory usage due to call stack
โ Risk of stack overflow if no proper base case
โ Python has a recursion limit (default: 1000 calls)
๐น Changing Recursion Limit (optional)
import sys
sys.setrecursionlimit(2000)
โญ When to Use Recursion?
Use recursion when the problem:
โ can be defined in terms of smaller subproblems
โ involves repeated substructure
โ suits tree-like or mathematical patterns
Examples:
- Factorial
- Fibonacci
- Tree traversals
- Searching (DFS)
- Divide and conquer algorithms
๐ Exam-Ready Summary
- Recursion = function calling itself
- Two parts: Base Case + Recursive Case
- Uses call stack
- Good for mathematical & tree problems
- Needs stopping condition to avoid infinite loop
- Less efficient than loops but more elegant
