← Back to course
Code Crew G5 / Week 03 / Friday
5/6
Week 03 Β· Nesting boxes

Friday

Recursive staircase
// A function that calls itself
⏱ about 15 min

Friday: Recursive staircase

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

Repeating a string

In Python, a string times a number repeats the string. So "*" * 3 makes "***".

print("*" * 3)
print("ab" * 2)
Output:
***
abab

The staircase

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.

How many rows does stairs(3) print?
How many stars does stairs(4) print in total?

Flip the staircase

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)
What goes in the blank?
WHY THIS EXERCISEThe call still shrinks by one, but now each row prints after the smaller staircase returns.
THINK ABOUT STAIRS_UP(3).
  • Read the question.
  • Tap your answer.
Which row prints first?
At the computer
With a grown-up, run stairs and stairs_up in IDLE.
Try a bigger number like 8. Then try changing "*" to "#".
How many rows does stairs(6) print?
How many stars does stairs(5) print in total?
How many stars are in the last row of stairs_up(5)?
What does print("#" * 4) show?
STAIRCASE CHECK
  • Read the question.
  • Tap your answer.
What does print("ab" * 3) show?
In stairs, which part is the stopping point?
What would stairs(n + 1) do in place of stairs(n - 1)?
Which row does stairs_up(4) print last?
StatementTrue 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.?
WHY THIS EXERCISEBoth functions draw one row per call. Only the order changes.

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.

← Thursday