What is Recursion?
Recursion is when a function calls itself to solve smaller parts of a problem — ideal for tasks that can be broken down into repetitive subproblems.
✅ Basic Recursive Structure
def function_name():
# base condition
if condition:
return something
else:
return function_name() # recursive call
Without a base condition, the function will keep calling itself forever — causing a RecursionError.
💡 Example 1: Factorial Using Recursion
def factorial(n):
if n == 0 or n == 1: # base case
return 1
else:
return n * factorial(n - 1)
print(factorial(5)) # Output: 120
Here’s how it works:
factorial(5)
→ 5 * factorial(4)
→ 5 * 4 * factorial(3)
→ 5 * 4 * 3 * factorial(2)
→ ...
→ 5 * 4 * 3 * 2 * 1 = 120
💡 Example 2: Fibonacci Series Using Recursion
def fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)
for i in range(7):
print(fibonacci(i), end=' ') # Output: 0 1 1 2 3 5 8
🔨 Mini Project:
Factorial & Fibonacci Calculator
def factorial(n):
return 1 if n <= 1 else n * factorial(n - 1)
def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n - 1) + fibonacci(n - 2)
num = int(input("Enter a number: "))
print("Factorial:", factorial(num))
print("Fibonacci:", fibonacci(num))
So clear! Recursion always clicks better for me with visual examples - do you use any tools or diagrams to help see the call stack when debugging?