Comet has already run three versions of a loop this morning. Each time the total surprised her.
"I just keep pressing F5 until it looks right," she admits, laughing. "That is faster, isn't it?"
Wren slides his clipboard across the table. It holds a grid with a column for every variable. "What does the evidence say?" he asks. "Your runs show the end. A trace shows every step on the way."
Nova projects an empty trace table beside the code. "How can I help?" she asks. "Fill in one row for each pass, then let the computer check you."
Comet picks up her pencil from behind her ear. "Fine. Lead programmer, you take the first row."
A trace table has one column for each variable and one row for each step. You fill it in by hand while you follow the program.
When you trace first, your prediction is ready before the computer answers. A surprise then tells you exactly where your thinking split from the code.
# trace_loop.py
grams = [42, 18, 65]
total = 0
for g in grams:
total = total + g
print(total) | Step | g | total |
|---|---|---|
| before the loop | (no value yet) | 0 |
| pass 1 | 42 | 42 |
| pass 2 | 18 | 60 |
| pass 3 | 65 | 125 |
125
A statement execution count is how many times a line runs. You can work it out by tracing.
Counting this way is a simple, informal way to compare how much work different loops do. Watch the count when one loop sits inside another.
# trace_nested.py
count = 0
for row in range(2):
for col in range(3):
count += 1
print(row, col)
print("count", count) 0 0 0 1 0 2 1 0 1 1 1 2 count 6
Comet's sample log will start as dicts tomorrow, so here is a quick review. Predict each line, then check with the run.
kinds["S01"] reads the value stored under the key "S01". The run shows what get and items give back.
# dict_review.py
kinds = {"S01": "basalt", "S02": "quartz"}
print(kinds["S01"])
print(kinds.get("S02"))
print(kinds.get("S09"))
print(kinds.get("S09", "none yet"))
for label, kind in kinds.items():
print(label, kind) basalt quartz None none yet S01 basalt S02 quartz
| Statement | True or false? |
|---|---|
| A line inside a loop can run more than once. | ? |
| In trace_nested.py, count += 1 runs 2 times. | ? |
| dict_review.py stops with an error at kinds.get("S09"). | ? |
| The items() loop gave each label and its kind together. | ? |
Tracing is a habit that saves runs and explains surprises. Tomorrow is Sim Lab, and Comet's first FieldSim prototype.