Menu

Output

Working Out Program Output

To work out a program's output, follow the code one statement at a time, from top to bottom. For each statement, update the value of any variable it changes. When you reach a print() call, work out what it would show — quoted text as written, a variable's current value, or an expression calculated first — and note that down before moving on.

The order matters because a variable can hold one value early in a program and a different value later. A print() call never changes a variable, but an assignment such as boxes = boxes + 3 does. Keep a running record of every value so you never use an old one by mistake.

boxes = 6
boxes = boxes + 3
print("Boxes counted")
print(boxes)
boxes = boxes * 4
print(boxes - 5)

Output:

Boxes counted
9
31

Track values with a trace table

A trace table records the value of each variable, and any output, after every statement. That makes it clear which value each print call uses.

StatementValue of boxesOutput
Start6none
boxes = boxes + 39none
print("Boxes counted")9Boxes counted
print(boxes)99
boxes = boxes * 436none
print(boxes - 5)3631

At the print(boxes) call, boxes holds 9, so 9 appears on screen. The next assignment changes it to 36, so the last print call starts from 36, works out 36 - 5, and prints 31. Reading the print calls out of order, or skipping an assignment in between, gives the wrong output.

Practise this