Python Recursion with example

Python recursion is a technique where a function calls itself repeatedly until a specific condition is met. This can be useful for solving problems that can be broken down into smaller, similar sub-problems. Here’s an example of a recursive function in Python:

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

print(factorial(5))

In this example, we’re defining a recursive function factorial that calculates the factorial of a number. The factorial of a number is the product of all positive integers up to and including that number. For example, 5! (read “5 factorial”) is 5 x 4 x 3 x 2 x 1, which equals 120.

The factorial function takes one parameter n, which is the number we want to calculate the factorial of. Inside the function, we have a base case and a recursive case. The base case is when n is equal to 0. In this case, we return 1, because the factorial of 0 is 1 by definition.

The recursive case is when n is greater than 0. In this case, we return n multiplied by the result of calling factorial with n-1 as the argument. This means that we’re calling the factorial function again with a smaller value of n, and multiplying the result by n. This process continues until we reach the base case (when n is equal to 0), at which point the function returns 1 and the recursion stops.

When we call the factorial function with factorial(5), the output will be 120, which is the factorial of 5. The function called itself five times (once for each integer from 5 down to 1) to calculate the final result.

Recursion can be a powerful technique, but it’s important to use it carefully, as it can easily lead to infinite loops if the base case is not well-defined or if the recursion depth becomes too large.

Leave a Reply