Comet pins three printouts to the board. Each one is a bug from the crew's first week.
"One would not start at all," she says. "One stopped in the middle. And one ran fine but gave the wrong total. That last one is the sneakiest!"
Wren studies the three pages. "What does the evidence say?" he asks. "They are different kinds of mistake, so they need different ways to find them."
Nova projects three labeled bins on the wall. "How can I help?" she asks. "Read each program, then sort it into a bin."
Comet hands you the first page. "Lead programmer, which bin?"
# syntax_demo.py
print("Start")
grams = [42, 18, 65, 7]
for g in grams
print(g) File "syntax_demo.py", line 4
for g in grams
^
SyntaxError: expected ':' Look closely at the run. Start never printed, even though print("Start") is on line 2.
The mistake was found before the first line ran. A compiler checks code for some errors in the same way, before the program runs.
# index_demo.py
grams = [42, 18, 65, 7]
print("Last:", grams[3])
print("Next:", grams[4]) Last: 7
Traceback (most recent call last):
File "index_demo.py", line 4, in <module>
print("Next:", grams[4])
~~~~~^^^
IndexError: list index out of range IndexError means a list index is out of range. The list has four items, and the run shows grams[3] worked while grams[4] stopped the program.
This program is meant to total all four samples, 132 g. It runs with no message at all. Compare its output with what it should show.
# logic_demo.py
grams = [42, 18, 65, 7]
total = 0
for i in range(len(grams) - 1):
total += grams[i]
print(f"Total: {total} g") Total: 125 g
The fix is to loop over range(len(grams)). The run of the fixed version matches the expected total.
# logic_demo.py, fixed
grams = [42, 18, 65, 7]
total = 0
for i in range(len(grams)):
total += grams[i]
print(f"Total: {total} g") Every error kind has its own clue: a message before the start, a message partway, or a wrong answer. Tomorrow is Trace Friday.