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."
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!
| Job | Loop version | Recursion version |
|---|---|---|
| When to stop | the test n > 0 becomes False | the base case n == 0 |
| Get smaller | n = n - 1 | countdown(n - 1) |
| Work each time | print(n) | print(n) |
| At the end | print("Liftoff!") after the loop | print("Liftoff!") in the base case |
| Statement | True 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. | ? |
def tick_loop(n):
while n > 0:
print("tick", n)
n = n - 2
print("done")
tick_loop(5) | Statement | True 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. | ? |
Nicely matched! Loops and recursion share the same big ideas. Tomorrow we add up numbers both ways.