← Back to course
Code Crew G5 / Week 05 / Monday
1/6
Week 05 Β· Loop or recursion?

Monday

Countdown two ways
// The same job, two ways
⏱ about 15 min

Monday: Countdown two ways

Two probes are ready to launch at once. Rocket wrote one countdown with recursion. Raven wrote hers with a loop.

"Mine is better," Rocket says with a grin. "Recursion is the new thing!"

Raven runs both. The screens show the same numbers. "What do you notice about the two programs?"

"They both stop at 0," says Rocket. "And they both take away 1 each time."

Nova projects them side by side. "Here is a hint. Match each part of one program to a part of the other."

The while loop

A while loop repeats its lines as long as its test is True. When the test becomes False, the loop ends.

The lines inside must change something, or the test would stay True forever.

def countdown_loop(n):
    while n > 0:
        print(n)
        n = n - 1
    print("Liftoff!")

countdown_loop(3)
Output:
3
2
1
Liftoff!

Side by side

JobLoop versionRecursion version
When to stopthe test n > 0 becomes Falsethe base case n == 0
Get smallern = n - 1countdown(n - 1)
Work each timeprint(n)print(n)
At the endprint("Liftoff!") after the loopprint("Liftoff!") in the base case
MATCH THE PARTS.
  • Read the question.
  • Tap your answer.
In the loop version, which line does the job of the smaller step?
In the loop version, what decides when to stop?
For countdown_loop(6), how many times do the lines inside the while loop run?
WHY THIS EXERCISEWhen n reaches 0, the test n > 0 is False, so the loop stops.
StatementTrue or false?
countdown_loop(3) and countdown(3) print the same lines.?
The loop version calls itself.?
If we deleted n = n - 1, the loop would never end.?
WHY THIS EXERCISEA loop needs a change that leads to stopping, just as recursion needs a smaller step.

Practice lab: a loop that hops

def tick_loop(n):
    while n > 0:
        print("tick", n)
        n = n - 2
    print("done")

tick_loop(5)
How many lines does tick_loop(5) print?
What number is in the last tick line?
What is n when the loop ends for tick_loop(5)?
How many times does the loop body run for tick_loop(6)?
LOOP CHECK
  • Read the question.
  • Tap your answer.
Which line makes n smaller?
When does print("done") run?
What does tick_loop(0) print?
StatementTrue or false?
tick_loop calls itself.?
The while test is checked before each pass.?
tick_loop(4) prints tick 4 and tick 2.?
If we changed n - 2 to n + 2, the loop would end sooner.?
WHY THIS EXERCISEThe change inside a loop must lead to the test becoming False.
How many tick lines does tick_loop(9) print?
WHY THIS EXERCISEThe loop runs for each odd number from 9 down to 1.

Nicely matched! Loops and recursion share the same big ideas. Tomorrow we add up numbers both ways.