Recursion Function
Last Updated: 02th September 2025
Recursion is a technique where a function calls itself to solve a problem. It is a way to break down a problem into smaller subproblem and solve them one by one.
Hinglish Tip 🗣: Ek aisa function jo khud to call kre,aur ek bade se problem ko ek ek chhote part me break kre.
🧱 Syntax Pattern
def func(params):
if base_condition:
return base_value # 🛑 Stop
return combine( func(smaller_params) ) # 🔁 Recurse with progress
Example 1.
# factorial
def factorial(n):
if n == 0 or n == 1: # base case
return 1
return n * factorial(n - 1) # recursive case
print(factorial(5)) # 120
Example 2.
# sum of list
def sum_list(nums):
if not nums: # base: empty list
return 0
return nums[0] + sum_list(nums[1:])
print(sum_list([3, 5, 7, 9])) # 24
Example 3.
# Fibonacci sequence
def fibonacci(n):
if n == 0:
return 0
if n == 1:
return 1
return fibonacci(n - 1) + fibonacci(n - 2)
print(fibonacci(6)) # 8