Recursion in Python

Recursion means that a function calls itself during its execution. It is used to solve problems that can be broken down into smaller, similar problems.

Every recursive function must have:

  • Base Case: A condition to stop the recursion.
  • Recursive Case: The part where the function calls itself.

Syntax:

def function_name():
    if condition:
        return value         # base case
    else:
        return function_name()  # recursive call

Example: Find factorial using recursion

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

print("Factorial of 5 is:", factorial(5))

Output:

Factorial of 5 is: 120

Explanation:

  • factorial(5) calls factorial(4), which calls factorial(3), and so on.
  • When n == 1, it returns 1 (base case).
  • The results are multiplied as the function returns back step-by-step.
  • So, 5×4×3×2×1 = 120.

Fibonacci Series using Recursion

The Fibonacci Series is a sequence where each number is the sum of the two previous numbers. It starts with 0 and 1.

Formula: F(n) = F(n-1) + F(n-2)

Example Sequence: 0, 1, 1, 2, 3, 5, 8, 13, ...

Syntax:

def fibonacci(n):
    if n <= 1:
        return n
    else:
        return fibonacci(n-1) + fibonacci(n-2)

Example: Print first 6 terms

def fibonacci(n):
    if n <= 1:
        return n
    else:
        return fibonacci(n-1) + fibonacci(n-2)

print("Fibonacci series:")
for i in range(6):
    print(fibonacci(i))

Output:

Fibonacci series:
0
1
1
2
3
5

Explanation:

  • fibonacci(0) returns 0
  • fibonacci(1) returns 1
  • Next terms: 1 (0+1), 2 (1+1), 3 (1+2), 5 (2+3)
  • Each function call makes two smaller recursive calls until n <= 1.

Key Points to Remember:

  • Recursion is used when a task can be divided into similar smaller tasks.
  • It must always have a base case, otherwise it may go into infinite calls and crash.
  • Recursion is useful for problems like factorial, Fibonacci, tower of Hanoi, etc.
  • It can sometimes be less efficient than loops if not used properly.

Welcome to ShikshaSanchar!

ShikshaSanchar is a simple and helpful learning platform made for students who feel stressed by exams, assignments, or confusing topics. Here, you can study with clarity and confidence.

Here, learning is made simple. Notes are written in easy English, filled with clear theory, code examples, outputs, and real-life explanations — designed especially for students like you who want to understand, not just memorize.

Whether you’re from school, college, or someone learning out of curiosity — this site is for you. We’re here to help you in your exams, daily studies, and even to build a strong base for your future.

Each note on this platform is carefully prepared to suit all levels — beginner to advanced. You’ll find topics explained step by step, just like a good teacher would do in class. And the best part? You can study at your pace, anytime, anywhere.

Happy Learning! – Team ShikshaSanchar