Tracing the calls
Python · Unit 11: Recursion
- Full plan
- Python
- 9 exercises
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. Multiple choice
While
fact(2)is working, what happens to the callfact(3)?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. Predict the output
What does this code print?
4. Predict the output
Follow what each call returns. What does it print?
5. Complete the code
Fill in the base case so it prints 8, which is 2 to the power of 3.
6. Find the bug
This program should print 24, the factorial of 4. Which line has the bug?
7. Put the lines in order
Put it in order so it draws a staircase going down: #, ## and ###, in that order.
8. Multiple choice
With
countdown(4), how many times iscountdowncalled in total, counting the first?9. Predict the output
What does this code print?
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.