Skip to the content

Tracing the calls

Python · Unit 11: Recursion

When fact(3) calls fact(2), it doesn't finish: it waits for the answer. Each call has its own n.

Calls pile up like plates: the last one in is the first one out. That's the call stack.

def fact(n):
    print("in", n)
    if n == 1:
        return 1
    r = n * fact(n - 1)
    print("out", n)
    return r

fact(3)

Prints

in 3
in 2
in 1
out 2
out 3

The rest of the explanation is in the lesson, which is part of the full plan.

Exercises in this lesson

You do them in the app, which checks them on the spot and explains why.

  1. 1. Multiple choice

    While fact(2) is working, what happens to the call fact(3)?

  2. 2. Predict the output

    Here the base case is doing nothing, because with 0 it doesn't go into the if. What does it print?

  3. 3. Predict the output

    What does this code print?

  4. 4. Predict the output

    Follow what each call returns. What does it print?

  5. 5. Complete the code

    Fill in the base case so it prints 8, which is 2 to the power of 3.

  6. 6. Find the bug

    This program should print 24, the factorial of 4. Which line has the bug?

  7. 7. Put the lines in order

    Put it in order so it draws a staircase going down: #, ## and ###, in that order.

  8. 8. Multiple choice

    With countdown(4), how many times is countdown called in total, counting the first?

  9. 9. Predict the output

    What does this code print?

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →