The base case is the branch that returns without calling itself. It is the smallest input whose answer you already know, and it is what makes the recursion end.
What you will see
0
About 3 min of reading
Quick check
Before this new lesson, one small question about the lesson you just finished. Recall it, do not look it up.
Try It
Write base cases that end cleanly.
1
Sum an empty list.
def total(a):
if not a:
return 0
return a[0] + total(a[1:])
print(total([]))
Before you run it, say out loud what it will print. Then open the answer.
Before you run it, say out loud what it will print. Then open the answer.
What it prints
9
3
Fib of 6.
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
print(fib(6))
Before you run it, say out loud what it will print. Then open the answer.
What it prints
8
4
Call with zero.
def h(n):
if n <= 0:
return 0
return h(n - 1)
print(h(0))
Before you run it, say out loud what it will print. Then open the answer.
What it prints
0
Put it in order
Before you write anything, put these lines back in the right order. Click a line to move it up one step. This support step is easier than writing code from scratch, and it is here to make the last example stick.
Data Flow
The base case returns a known answer without recursing. It must be reachable and must match how the recursive call shrinks the input.
1smallest input
↓
2return known answer
↓
3no further call
↓
4chain ends
Line by line
Read the first example one line at a time. A line that prints shows what appears on screen; the rest set things up quietly.
def total(a):sets nothing on screen
if not a:sets nothing on screen
return 0sets nothing on screen
return a[0] + total(a[1:])sets nothing on screen
print(total([]))0
Why this worksKnow the smallest answer
Pick the input so small that you can state the answer with no recursion. That is your base case, and it must be reachable.
Match the shrink
The base test has to line up with how the recursive call reduces the input. Step by two and test for zero is a mismatch.
Examples
Empty is the base
deftotal(a):
if not a:
return0return a[0] + total(a[1:])
print(total([2, 3]))
An empty list sums to zero. That base case ends the chain of calls.