Exercise 1: Tracing calls: the order in which the lines run
A def statement only defines a function: its body runs when the function is called, and every call ends by sending its value back to the place of the call. Trace the program below without running it.
def square(n): # line 1
print('square of', n) # line 2
return n * n # line 3
def sum_of_squares(a, b): # line 4
total = square(a) + square(b) # line 5
return total # line 6
result = sum_of_squares(3, 4) # line 7
print(result) # line 8
print(square(square(2))) # line 9- a) How many lines does the program print? What is the first of them?
- b) What value does square(a) return the first time line 5 calls it? What does line 8 print?
- c) What does line 9 print, line after line?
- d) How many times does line 2 run in the whole program?
- e) At the moment line 2 runs for the first time, which calls have started and not yet finished? What value does n hold in the call that is running?
Show the solution
Answers
- a) 6 lines; the first is square of 3
- b) 9; 25
- c) square of 2, then square of 4, then 16
- d) 4 times
- e) the main program, sum_of_squares(3, 4) and square(3); n = 3
Lines 1 to 6 only define the two functions: nothing is printed and no body runs. The program starts its work at line 7, and each call is followed into the body of the function, then back to the place of the call with the value returned.
Line 7 calls sum_of_squares(3, 4). Line 5 calls square(3), whose line 2 prints square of 3, then square(4), which prints square of 4. total is 9 + 16 = 25.
Line 8 prints 25. Line 9 prints three lines (part c).
The program prints 2 + 1 + 3 = 6 lines, and the first is square of 3.
Pitfall: starting the trace at line 1 and printing something for a def. A def creates the function, it does not call it.
The first call of line 5 is square(a) with a = 3: n receives 3 and line 3 returns 3 * 3 = 9.
The second call, square(4), returns 16, and total = 9 + 16 = 25 is returned by line 6 to line 7: result holds 25, which line 8 prints.
A call written inside another call runs first, since its value is the argument of the outer call.
square(2) prints square of 2 and returns 4; then square(4) prints square of 4 and returns 16; print displays 16.
Pitfall: reading the line from left to right and printing square of 4 first. The outer square cannot start before it knows its argument.
Line 2 runs once per call of square: twice from line 5 (for 3 and for 4), twice from line 9 (for 2 and for 4). 4 times.
The main program is stopped at line 7, waiting for sum_of_squares(3, 4); that call is stopped at line 5, waiting for square(3); square(3) is the one running, with n = 3.
The figure shows this call stack: the call running sits on top, and each call below it waits for the value of the call above it. When square(3) returns 9, its frame is removed and sum_of_squares goes on from line 5.