Debugging

How to read a traceback and look for the cause, not the symptom.

Debugging starts with reading the error, not with rewriting the code. In a traceback, look at the last line (the type and the message) and at the last line from your own file in the chain of calls. Lines from the standard library are almost never to blame: the error reached them from your code.

If there is no error but the result is wrong, narrow down the search:

  • print intermediate values with print(f"{total=}");
  • test the function on its own with a small example whose answer you know in advance;
  • comment out half of the code and see whether the problem is still there.

assert checks an assumption and fails if it is false: assert len(items) > 0, "empty list". It is a way to write down in code what you believe to be true. But assert is not suitable for checking user input: it can be switched off with a startup flag.

The mistakes you will meet most often:

  • Off by one. range(1, 10) does not include 10, and the last index of a list is len(items) - 1.
  • Two names for one list. Changing the "copy" changes the original (the lesson on lists).
  • Division. / always gives a fraction, while // rounds down.
  • Empty data. Dividing by len([]), max([]), the first element of an empty list.
  • Indentation. A line that should be inside the loop ended up after it, or the other way round.

A good technique is to explain the code out loud, line by line, as if the listener knew nothing. The bug is often on exactly the line where the explanation does not match the code.

Practice

  1. Where to start reading

    Which part of a traceback should you start with?

    • The last line: the type and message of the error
    • The first line: Traceback (most recent call last)
    • The lines from the standard library
    • You can skip the traceback, restarting the program is enough
  2. How many numbers

    What does the program print?

    print(len(range(1, 10)))
    
  3. Fix the average

    The function average(nums) crashes on an empty list and returns fractions that are too long. Fix it: for an empty list return 0, otherwise return the average rounded to two digits.