Python Mastery โ€“ From Basics to Brilliance / Functions

Recursion in Python

๐Ÿ”„ Recursion

Recursion is a technique where a function calls itself to solve a problem.

A recursive function needs two important parts:

  1. ๐Ÿ›‘ Base Case โ†’ Stops the recursion

  2. ๐Ÿ” Recursive Case โ†’ Function calls itself


๐Ÿ”น Basic Example

def countdown(n):
    if n == 0:          # Base Case
        return

    print(n)
    countdown(n - 1)    # Recursive Case

countdown(5)
5
4
3
2
1

The function keeps calling itself until n becomes 0.


๐Ÿงฎ Factorial Using Recursion

Factorial of 5:

5! = 5 ร— 4 ร— 3 ร— 2 ร— 1 = 120
def factorial(n):
    if n == 1:              # Base Case
        return 1

    return n * factorial(n - 1)

print(factorial(5)) #120

โš ๏ธ Why is the Base Case Important?

Without a base case, the function keeps calling itself indefinitely.

def example():
    example()

example()

This eventually causes a RecursionError.


โญ Remember

Every recursive function should have a clear base case to stop the recursion.