Repaso
Español
Algorithms & DSCoreALG-44

Why must every recursive function have a base case?

def countdown(n):
    if n == 0:          # base case
        return
    print(n)
    countdown(n - 1)    # recursive case

Options

  1. It makes the function run faster on large inputs
  2. Without it, the calls never stop (RecursionError) (Correct option)
  3. Python requires it as part of the function syntax
  4. It lets the function return a value to its caller

Answer

Without a condition that stops the recursion, the function calls itself forever (RecursionError)

Why

Recursion means a function calls itself on a smaller version of the problem.

The base case is the simplest input that is answered directly, without another call (here n == 0). Each call must move closer to it.

Without a base case, the calls never stop and Python raises RecursionError when the call stack is too deep.

Remember

Recursion = base case + smaller recursive call.

Key terms

Practice this question in Repaso