Lesson 5.14 · Trace it
Trace: stack moves
Python code13 rows to fill3 marks
Complete the trace table for this Python code. stack is used as a stack, and its last value is the top. append pushes a value onto the top, and pop() takes the top value off and gives it back. Write the stack in square brackets, bottom first, as Python prints it. Then answer the question below the table. [3]
Line 1: stack = []Line 2: stack.append(6)Line 3: stack.append(1)Line 4: x = stack.pop()Line 5: stack.append(8)Line 6: stack.append(x + 3)Line 7: total = 0Line 8: while len(stack) > 0:Line 9, indented 1 level: top = stack.pop()Line 10, indented 1 level: total = total + top
Fill in one row each time a line changes stack, x or total. The table already has the right number of rows. In each row, write only what that line changes; you can leave the other cells empty or copy their values down. Write values the way Python shows them: 3 and 3.0 are different, and text goes in quotes.
| Row | stack | x | total |
|---|---|---|---|
| 1 | |||
| 2 | |||
| 3 | |||
| 4 | |||
| 5 | |||
| 6 | |||
| 7 | |||
| 8 | |||
| 9 | |||
| 10 | |||
| 11 | |||
| 12 | |||
| 13 |