← Back to course
Code Crew G5 / Week 03 / Wednesday
3/6
Week 03 Β· Nesting boxes

Wednesday

Countdown calls itself
// A function that calls itself
⏱ about 15 min

Wednesday: Countdown calls itself

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."

The countdown function

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!
  • countdown(3) prints 3, then calls countdown(2).
  • countdown(2) prints 2, then calls countdown(1).
  • countdown(1) prints 1, then calls countdown(0).
  • countdown(0) prints Liftoff! and does not call again. That is the stopping point.

Just like the crate, every call works on a smaller number. Just like the line, the last one does something different.

USE THE COUNTDOWN FUNCTION.
  • Read the question.
  • Tap your answer.
What does countdown(4) print first?
Which call prints Liftoff!?
How many lines does countdown(5) print in total?
WHY THIS EXERCISEThere is one call for each number from 5 down to 0, and each call prints one line.
def countdown(n):
    if n == 0:
        print("Liftoff!")
    else:
        print(n)
        countdown(____)

countdown(2)
What goes in the blank so each call works on a smaller number?
WHY THIS EXERCISEEach call must move closer to 0, or the countdown would never reach the stopping point.

Practice lab: two launches

def blastoff(n):
    if n == 0:
        print("Go!")
    else:
        print(n)
        blastoff(n - 1)

blastoff(2)
blastoff(1)
How many lines print in all?
What is the first line?
How many times does Go! print?
How many calls to blastoff happen in all?
LAUNCH CHECK
  • Read the question.
  • Tap your answer.
What does blastoff(0) print?
Suppose blastoff called blastoff(n + 1) instead. What would happen?
Which line checks for the stopping point?
StatementTrue 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.?
WHY THIS EXERCISEThere is one call for each number down to 0, and each call prints one line.
How many lines does blastoff(7) print?
WHY THIS EXERCISECalls for 7 down to 1 print numbers, and blastoff(0) prints Go!

You wrote your first recursion! Tomorrow we watch the calls pile up and come back down.

← Tuesday