Codzy

Recursion

A recursive function is a function that calls itself. You break a problem into a smaller version of the same problem: for example, 5! = 5 × 4!.

Every recursive function needs a base case, a situation where it stops without calling itself (here n <= 1). Without one, the function calls itself forever and Python raises a RecursionError. Recursion is very handy for trees, folders and some sorting algorithms.

def countdown(n):
    if n == 0:
        print("Go!")
        return
    print(n)
    countdown(n - 1)

countdown(3)

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

print(factorial(5))

Start the lesson