Skip to chapter content
navan✳THE BUILD LABPYTHON / GUIDE
0/26 read
CHAPTER 05 / 26 · FOUNDATIONS

Debugging with evidence.

Read a traceback, isolate the failing assumption, and verify the fix.

BY NAVAN SAMI5 MIN READTHEORY FIRST
01 / THE BASICS

Start here.

A program can stop with an exception or finish with an unexpected result. An exception is Python's way of reporting that an operation cannot continue normally. Its traceback lists the path of function calls and ends with a type and message, such as ZeroDivisionError: division by zero. The message tells you which rule was broken; the line number tells you where Python noticed it. Neither tells the whole story of why that input reached the line.

In the average example, sum(values) adds the numbers, and len(values) counts them. With [2, 4, 6], the sum is 12 and the length is 3, so division returns 4.0. With an empty list, both sum and length are zero. The expression 0 / 0 has no numeric result in ordinary Python division and raises ZeroDivisionError. The deeper question is what average should mean for an empty collection. A deliberate ValueError can state that the function does not accept that input.

Debugging is reasoning backward from evidence. Identify the actual value at the failing operation, then ask where it came from and which assumption was false. For a wrong result, trace a small input through each assignment and branch. A focused print or log can reveal a value without changing the underlying rule. A test records an expected behavior for future changes, but the skill here is understanding the data path well enough to explain both the intended result and the failure.

02 / THE IDEA

Build the model.

A bug is a mismatch between what a program does and what you meant it to do. When Python raises an exception, the traceback gives a path of calls ending at the line where execution failed. Read the final exception type and message first, then move upward to see how the program arrived there. A line number is a starting point for investigation, not proof that the whole problem lives on that line.

For a wrong result without an exception, write down a small input and the expected output. Inspect intermediate values, add a focused print or logging statement, and compare the actual path with your expectation. Once you know the cause, make the smallest change that explains it and rerun the small case plus a nearby edge case.

03 / UNDER THE SURFACE

How it works.

Exceptions describe categories of failure. ValueError often means a value cannot be used as requested; KeyError means a dictionary key was absent; TypeError often means an operation received an unsuitable type. Catch an exception only where you can choose a useful recovery. Catching every exception and returning a plausible value can hide a real defect.

A test records a claim about behavior. It can check a normal case, a boundary, and an expected failure so a later edit cannot silently break the contract. Logging is useful for persistent programs because it records what happened without requiring someone to watch the terminal. Both are tools for evidence, not substitutes for understanding the code path.

04 / A WORKED EXAMPLE

Read it line by line.

example.py
def average(values):
    return sum(values) / len(values)

print(average([2, 4, 6]))

The function sums the three values to 12, divides by length 3, and prints 4.0. Now call average([]): sum is 0 and len is 0, so division raises ZeroDivisionError. That small failing case reveals a missing contract decision. The correct fix depends on whether an empty collection should be rejected or given a defined result.

05 / ANOTHER EXAMPLE

See the rule again.

example-2.py
def average(values):
    if not values:
        raise ValueError('average needs at least one value')
    return sum(values) / len(values)

print(average([2, 4, 6]))

The normal result remains 4.0. An empty input now raises a deliberate ValueError that explains the violated contract instead of an accidental division error. A caller can handle that specific exception where it asks the user for new input.

06 / REMEMBER THIS

A mistake to avoid.

Do not silence an error by wrapping a large function in bare except. It may catch a typo or programming defect and turn it into misleading normal output.

Finished this chapter?
Built with curiosity. By Navan Sami. ↗Python · Understand the idea, then write the code.