Nova wants a picture for the probe log: a staircase made of stars.
Rocket starts typing print lines with stars. "Four stars, then three, then two," he mutters. "This is a lot of typing."
Raven sketches the stairs. "What do you notice if you cover the top step?"
"The rest is a smaller staircase!" Rocket says.
Nova blinks twice. "Here is a hint. Draw one row, then let a smaller staircase do the rest."
In Python, a string times a number repeats the string. So "*" * 3 makes "***".
print("*" * 3)
print("ab" * 2) Output: *** abab
def stairs(n):
if n == 0:
return
print("*" * n)
stairs(n - 1)
stairs(4) Output: **** *** ** *
When n is 0, return ends the call with nothing to print. That is the stopping point.
Every other call draws one row of n stars, then asks stairs(n - 1) to draw the rest.
Move the print after the call, like count_up. The short rows now print first.
def stairs_up(n):
if n == 0:
return
stairs_up(____)
print("*" * n)
stairs_up(3) | Statement | True or false? |
|---|---|
| stairs(0) prints nothing. | ? |
| stairs(2) prints 3 rows. | ? |
| stairs and stairs_up print the same rows in a different order. | ? |
| "*" * 1 makes one star. | ? |
Week 3 complete! You pictured recursion with boxes and a line of crew, then wrote it in Python. Next week we study the stopping point closely.