Debugging Strategies

Python 3.14 · ✓ verified by execution on 2026-07-25

Bugs are a natural part of programming. When your code doesn’t do what you expect, you need strategies to track down the root cause.

The assert Statement

Assert statements are a convenient way to insert debugging assertions into a program. They help you verify that your assumptions about the state of your program are correct.

The simple form, assert expression, evaluates the expression. If it is true, nothing happens. If it is false, Python raises an AssertionError.

python
assert True
print('Pass')
Output
Pass

If an assertion fails, execution stops immediately, pointing you directly to the broken assumption:

python
assert False, 'Expected failure'
This example raises an error (on purpose)
AssertionError

Unambiguous Printing with repr()

When debugging by printing, a common pitfall is that print() implicitly converts objects to strings intended for end-users. This can hide important details, like whether a value is the number 5 or the string "5".

To avoid ambiguity, use the repr() function. It returns a string containing a printable representation of an object. For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval().

python
# Notice how repr shows the newline character explicitly!
print(repr('hello\nworld'))
Output
'hello\nworld'

A class can control what this function returns for its instances by defining a __repr__() method.

python
class MyClass:
    def __repr__(self):
        return 'MyClass()'

print(repr(MyClass()))
Output
MyClass()

By wrapping your variables in repr() before printing, you guarantee you are seeing exactly what Python sees.

python
lst = [1, 2, 3]
import ast
print(ast.literal_eval(repr(lst)) == lst)
Output
True

Conceptual Strategies

Binary Search Debugging: If you have a long sequence of code or data causing an error, don’t check every line from top to bottom. Instead, check the middle. If the state is correct halfway through, the bug must be in the second half. This “binary search” approach halves the search space at each step.

python · visualize
def binary_search_debug(arr, target):
    # Simulate debugging by printing middle state
    mid = len(arr) // 2
    print(f'Checking mid={mid} value={arr[mid]}')
    return target == arr[mid]

binary_search_debug([1, 2, 3], 2)

Rubber Duck Debugging: When you are completely stuck, try explaining your code line-by-line to an inanimate object, like a rubber duck. The process of slowing down and verbalizing your logic often makes the hidden flaw completely obvious.

Check yourself

What does the assert statement do?

Reveal answer

It evaluates an expression and raises AssertionError if it is False. — The simple form, assert expression, evaluates the expression and raises AssertionError if it is false.

Why is repr() often better than str() or print() for debugging?

Reveal answer

It returns an unambiguous string representation of the object, often including quotes or type information. — repr() makes an attempt to return a string that would yield an object with the same value, making it unambiguous. For example, repr("5") shows quotes around the string, while print("5") looks identical to print(5).

What is Rubber Duck Debugging?

Reveal answer

Explaining your code line-by-line to an inanimate object to help spot logic errors. — Rubber duck debugging is an informal technique where you explain your problem out loud. The act of verbalizing often forces you to realize the flaw in your logic.

Challenges

Challenge 1 +15 XP

Fix the function by adding an assertion that checks if 'x' is positive.

python
  • Test 1 — expects "5.0\n"
Need a hint? (−25% XP)

Use the 'assert' keyword followed by a condition.

Show solution (0 XP)
def divide_positive(x, y):
    assert x > 0, 'x must be positive'
    return x / y

# Test the function
print(divide_positive(10, 2))

Challenge 2 +15 XP

Write a class 'Point' with a custom __repr__ method that returns 'Point(x, y)'.

python
  • Test 1 — expects "Point(3, 4)\n"
Need a hint? (−25% XP)

Define the __repr__(self) method in the class.

Show solution (0 XP)
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def __repr__(self):
        return f'Point({self.x}, {self.y})'

# Test the class
print(repr(Point(3, 4)))