How to Learn Recursion by Example in Python


Here’s an example code in Python that demonstrates recursion:

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

print(factorial(5))  # Output: 120

This code defines a function factorial that calculates the factorial of a given number n. The factorial of a number is the product of all positive integers up to and including that number. For example, the factorial of 5 is 5 x 4 x 3 x 2 x 1 = 120.

The factorial function uses recursion to calculate the factorial. If n is equal to 0, it returns 1 (the base case). Otherwise, it calls itself with n-1 as the argument and multiplies the result by n (the recursive case).

Recursion is a powerful concept that can be used to solve many problems. However, it’s important to use recursion with caution, as it can lead to stack overflow errors if not implemented correctly.