Skip to content
Justice Tech School

Recursion

A recursive function solves a problem by calling itself with a smaller input. It must have a base case that stops the calls. Python limits the depth to about 1000 calls, so very deep recursion fails with RecursionError.

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

print(factorial(5))

def fib(n):
    return n if n < 2 else fib(n - 1) + fib(n - 2)

print([fib(i) for i in range(8)])

Result

120
[0, 1, 1, 2, 3, 5, 8, 13]

Exercise

Name the part that stops the calls.

if n <= 1:
    return 1  # the  case

Quiz Test

What happens with no base case?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.