Skip to main content

P01.8 · Errors, debugging and first tests

A free, illustrated module of 4 lessons and one interactive in P01 Python from Zero: Reading a traceback; Handling exceptions: try, except and raise; Debugging as a method; First tests.

P01.8 L0 · Foundation 4 lessons · about 100 min Live · in review

Part of P01 Python from Zero in the Programming and Data track.

A program can go wrong in three ways: it refuses to start, it stops with a traceback, or it prints a wrong answer and says nothing. These four lessons teach you to read a traceback from the bottom up, to catch the errors you expect with try and except and raise clear ones of your own, to find a bug by experiment instead of by staring, and to write tests that check your code against numbers worked out by hand, first with a runner written from scratch and then with pytest.

What you need first. Functions and the call stack (P01.4), modules and installing a package with pip (P01.5), lists and dictionaries (P01.6), and splitting text and reading a file (P01.7).

Lessons

  1. Reading a traceback P01.8.1 25 min

    When Python stops on an error it prints a traceback: the call stack at the moment of failure, oldest call first. Learn the three kinds of mistake, read a traceback from the bottom up, and meet the nine exceptions you will see most.

  2. Handling exceptions: try, except and raise P01.8.2 25 min

    A try statement catches an exception before it stops the program, and raise stops a function early with a clear message. Learn the flow of try, except, else and finally, catch only what you expect, and load a dirty data file without losing its good rows.

  3. Debugging as a method P01.8.3 25 min

    A wrong answer with no message is found by experiment, not by staring: reproduce it, shrink the input, predict each line, look, and halve the suspect region. Worked on a median with two planted bugs, with prints and the debugger.

  4. First tests P01.8.4 25 min

    A test is code that checks code against a value worked out by hand. Write tests for mean and median, run them with a runner built from scratch and then with pytest, compare floats with pytest.approx, and pin a bug so that it cannot come back.

The interactive

P01.8-X1 · Traceback explorer. Choose one of four inputs to a three-function program and step through it: the call stack builds, the failing line lights up and the traceback appears, each of its entries linked to the frame it reports. A switch wraps the call in try and except to show where the error is caught and which frames are thrown away. It lives in Reading a traceback.

Back to top