Rocket is writing a beeper for the docking bay. It should beep a few times, then say done.
"I think recursion fits," he says. "But what makes recursion actually work?"
Raven lays last week's countdown next to the staircase. "What do you notice that they both have?"
Rocket points. "They both stop when n is 0. And they both call themselves with n minus 1."
Nova shines a light on each part. "Here is a hint. Give those two parts names, and look for them every time."
Every working recursion has two parts. The base case is the stop. It does not call the function again.
The smaller step calls the function again on a smaller problem. Each call must get closer to the base case.
def beep(n):
if n == 0:
print("done")
else:
print("beep")
beep(n - 1)
beep(3) Output: beep beep beep done
| Part | Lines in beep | Job |
|---|---|---|
| Base case | if n == 0: print("done") | Stops the calls |
| Smaller step | beep(n - 1) | Calls again with a smaller n |
| Statement | True or false? |
|---|---|
| The base case calls the function again. | ? |
| The smaller step should move closer to the base case. | ? |
| beep(0) prints only done. | ? |
def tick(n):
if n == 0:
print("ring")
else:
print("tick", n)
tick(n - 1)
tick(2) | Statement | True or false? |
|---|---|
| tick has a base case. | ? |
| tick(3) prints ring before tick 3. | ? |
| The base case in tick does not call tick again. | ? |
| tick(1) prints two lines. | ? |
Great job naming the parts! Tomorrow we find out what happens when one part goes missing.