The first probe is ready to launch. Rocket wants a countdown from 3 on the big screen.
"I could write print(3), print(2), print(1)," he says. "But what if Mission Control wants to start at 100?"
Raven thinks of the crate. "What do you notice about a countdown from 3?"
"After I say 3, the rest is just a countdown from 2!" Rocket says.
Nova sparkles. "Here is a hint. A function can call itself with a smaller number."
Read each line slowly. Look for the place where countdown calls countdown.
def countdown(n):
if n == 0:
print("Liftoff!")
else:
print(n)
countdown(n - 1)
countdown(3) Output: 3 2 1 Liftoff!
Just like the crate, every call works on a smaller number. Just like the line, the last one does something different.
def countdown(n):
if n == 0:
print("Liftoff!")
else:
print(n)
countdown(____)
countdown(2) def blastoff(n):
if n == 0:
print("Go!")
else:
print(n)
blastoff(n - 1)
blastoff(2)
blastoff(1) | Statement | True or false? |
|---|---|
| blastoff(3) prints 3 before 2. | ? |
| blastoff(3) prints Go! first. | ? |
| Each call works on a number 1 smaller. | ? |
| blastoff(10) prints 11 lines. | ? |
You wrote your first recursion! Tomorrow we watch the calls pile up and come back down.