how do i do recursion in python

Recursion in Python is a technique where a function calls itself with a modified version of the original input until a base case is reached. A base case is a stopping point where the function can return an output without making any more recursive calls. The recursive case is the portion of the function where it calls itself with a modified input.

Here's an example of a function that calculates the factorial of a number using recursion:

main.py
def factorial(n):
    # base case
    if n == 0:
        return 1
    # recursive case
    else:
        return n * factorial(n-1)
131 chars
8 lines

In this example, the base case is when n == 0, and the function returns 1. Otherwise, the function makes a recursive call to factorial(n-1), calculating the factorial of the next lowest integer until it reaches the base case.

Here's an example of how to call the factorial function:

main.py
print(factorial(5))
# Output: 120
34 chars
3 lines

In this example, the factorial function is called with an input of 5, which results in the recursive calls factorial(4), factorial(3), factorial(2), factorial(1), and factorial(0). Since factorial(0) is the base case, it returns 1, which is then used to calculate the final result of 120.

gistlibby LogSnag