Python Recursion

ht‮ww//:spt‬w.theitroad.com

Recursion is a powerful technique in programming where a function calls itself to solve a problem. In Python, you can write recursive functions to solve a variety of problems. Recursive functions have two parts: the base case and the recursive case.

The base case is the simplest case of the problem, where the function does not call itself. The base case tells the function when to stop calling itself and return a value.

The recursive case is where the function calls itself with a smaller version of the problem. The recursive case continues to call itself until it reaches the base case.

Here's an example of a recursive function to calculate the factorial of a number:

def factorial(n):
    # base case
    if n == 0:
        return 1
    # recursive case
    else:
        return n * factorial(n-1)

In this example, the base case is when n == 0. In that case, the function returns 1. The recursive case is when n > 0. In that case, the function multiplies n by the result of calling factorial with n-1. This continues until the base case is reached.

Here's an example of using the factorial function:

print(factorial(5))  # Output: 120

This example calls the factorial function with the argument 5. The function calculates 5 * 4 * 3 * 2 * 1 using recursion and returns the result, which is 120.

Recursive functions can be a powerful tool for solving problems in programming, but they can also be tricky to get right. It's important to make sure that your recursive function has a base case that will eventually be reached, or else your function will run indefinitely and cause a stack overflow error.