← Back to course
Code Crew G6+ / Week 10 / Crew Quest
6/6
Week 10 Β· Bugs and tests

Crew Quest

Crew Quest: Explain the bug
// Tracebacks, try and except, and assert
⏱ about 30 min

Saturday: Crew Quest: Explain the bug

Rocket has a bug he cannot find. He has stared at the code for twenty minutes. Raven has a strange suggestion: explain the program out loud, one line at a time, to someone who does not code.

"How can that help if they do not know Python?" Rocket asks.

Raven smiles. "What do you notice when you have to say exactly what each line does?" she asks. "You stop reading what you meant, and start reading what you wrote."

Nova settles on the desk to listen. "Programmers have done this for a very long time," she says. "Sometimes the listener is a person, sometimes a toy on the desk."

Halfway through line seven, Rocket stops talking and laughs. He has found it.

  1. Read a traceback from the bottom: the error name, then where it stopped, then the trail of calls.
  2. Logic bugs give no error. Compare the output with an answer worked out by hand.
  3. try and except catch an error you expect, like ValueError, and let the program carry on.
  4. assert checks a condition and stops with AssertionError if it is False.
  5. Keep tests in a separate file that imports your module.
# speed.py (has a bug)
def speed(distance, hours):
    return hours / distance

print(speed(100, 2))
speed(100, 2) should be 50 km per hour. What does the buggy program print?
WHY THIS EXERCISEThe division is upside down. Speed is distance divided by hours.
β—‡ EXPLAIN IT OUT LOUD
Pick any program you wrote this term. Explain it to a grown-up, one line at a time, saying exactly what each line does.
Ask your grown-up to stop you whenever something is not clear.
Then put the speed.py bug in front of them and explain it until one of you spots the problem. Write a test that would have caught it.
MORE REVIEW: WEEK 10
  • Read the question.
  • Tap your answer.
Where do you start reading a traceback?
int("abc") is inside try, with except ValueError. What happens?
assert 2 + 2 == 5 runs. What happens?

Superb work. Next week you start building Mission Log, the tool you will demo at graduation.

← Friday