Courses / Computer Science XII (HSSC-II) – FBISE Complete SLO-Based Course

3.8 Testing and Debugging: Unit Tests, Breakpoints and Watches

Unit 3 – Programming Fundamentals · 80 min read · 8 MCQs to check yourself

Corey Schafer – unit testing your code with the unittest module

Stop using print(): learn the VS Code debugger (breakpoints and watches)

1. Types of errors

Error When it appears Example
Syntax error Before running – code breaks the language rules print("hi" (missing bracket)
Runtime error (exception) While running – the program crashes 10 / 0, int("abc"), missing file
Logic error Program runs but gives the wrong answer Using + instead of *; range(1, n) missing the last value

Logic errors are the hardest – testing and debugging find them.

2. Unit testing

A unit test checks that one small unit (usually a function) gives the expected output for given inputs. The purpose: catch bugs early, prove the code works, and make sure later changes do not break it (regression testing).

Simple tests with assert:

def grade(marks):
    if marks >= 80: return "A"
    if marks >= 60: return "B"
    if marks >= 33: return "C"
    return "F"

assert grade(95) == "A"
assert grade(80) == "A"      # boundary value
assert grade(79) == "B"
assert grade(33) == "C"      # boundary value
assert grade(0) == "F"
print("All grade tests passed")

Output:

All grade tests passed

The unittest framework:

import unittest, sys

def average(values):
    if not values:
        return 0
    return sum(values) / len(values)

class TestAverage(unittest.TestCase):
    def test_normal(self):
        self.assertEqual(average([2, 4, 6]), 4)
    def test_single(self):
        self.assertEqual(average([7]), 7)
    def test_empty(self):
        self.assertEqual(average([]), 0)          # edge case
    def test_decimal(self):
        self.assertAlmostEqual(average([1, 2]), 1.5)

suite = unittest.TestLoader().loadTestsFromTestCase(TestAverage)
unittest.TextTestRunner(stream=sys.stdout, verbosity=2).run(suite)

Output:

test_decimal (__main__.TestAverage.test_decimal) ... ok
test_empty (__main__.TestAverage.test_empty) ... ok
test_normal (__main__.TestAverage.test_normal) ... ok
test_single (__main__.TestAverage.test_single) ... ok

----------------------------------------------------------------------
Ran 4 tests in 0.001s

OK

Good test cases cover normal values, boundary values (33, 80), edge cases (empty list, zero, negative) and invalid input.

3. Debugging with print statements

def total_price(prices, discount_percent):
    total = 0
    for p in prices:
        total += p
        print("DEBUG: p =", p, "total =", total)       # trace values
    result = total - total * discount_percent / 100
    print("DEBUG: before discount", total, "after", result)
    return result

print(total_price([200, 300, 500], 10))

Output:

DEBUG: p = 200 total = 200
DEBUG: p = 300 total = 500
DEBUG: p = 500 total = 1000
DEBUG: before discount 1000 after 900.0
900.0

Remove (or comment out) debug prints after fixing the bug.

4. IDE debugger: breakpoints, stepping and watches

Tool What it does Why it helps
Breakpoint Pauses the program at a chosen line (click beside the line number) Inspect the program at the exact moment before the bug
Step over Runs the current line, without going inside function calls Move line by line through the main logic
Step into Goes inside the function being called Check what a function does with its arguments
Step out Finishes the current function and returns Leave a function you have checked
Watch Shows the value of chosen variables/expressions while paused See exactly when a value becomes wrong
Call stack Shows which functions called which Understand how you reached a line
Conditional breakpoint Pauses only when a condition is true (i == 99) Catch a bug deep inside a long loop

Example: average_marks returns 64 instead of 80. Put a breakpoint on the return line, watch total and count – you see count = 5 but only 4 marks: the counter starts at 1 instead of 0. Fix and re-run the unit tests.

Popular Python IDEs with debuggers: IDLE, Thonny (very beginner-friendly), VS Code, PyCharm, Jupyter.

Short and long questions

1. A function average(marks) should return the average of a list of marks, but users report wrong results and a crash when the list is empty. Describe how you would use unit tests, print statements, breakpoints and watches to find and fix the problems, and write a corrected function with unittest test cases. (3 + 3)

Model answer

Process (3):

  1. Write unit tests for normal ([60, 80] → 70), single ([50] → 50), and edge cases ([] → 0) – the empty-list test reproduces the crash (ZeroDivisionError) and others reveal wrong results.
  2. Print debugging: print total and count inside the loop to see their values change.
  3. Breakpoint and watches: set a breakpoint on the return line, watch total and count; e.g. count starts at 1, so the divisor is too large (logic error). Step through the loop to confirm.
  4. Fix the code and re-run all tests (regression testing).

Corrected code with tests (3):

import unittest
def average(marks):
    if len(marks) == 0:
        return 0
    return sum(marks) / len(marks)

class TestAverage(unittest.TestCase):
    def test_normal(self): self.assertEqual(average([60, 80]), 70)
    def test_single(self): self.assertEqual(average([50]), 50)
    def test_empty(self):  self.assertEqual(average([]), 0)

unittest.main(argv=[""], exit=False)

2. How can print statements help to debug a program? Give an example.

Model answer

Printing variable values at key points shows how the data changes and where it first becomes wrong.

for i in range(1, 5):
    total = total + i
    print("DEBUG i =", i, "total =", total)

If total is unexpectedly large, the starting value of total or the loop range is wrong.

3. Differentiate between syntax, runtime and logic errors with one example each.

Model answer
  • Syntax error: breaks language rules; program will not start – if x > 5 print(x) (missing colon).
  • Runtime error: occurs while running and crashes the program – 10 / 0 (ZeroDivisionError).
  • Logic error: program runs but gives a wrong result – area = length + width instead of length * width.

4. Explain breakpoints and watches used in debugging.

Model answer
  • Breakpoint: a marker on a line where the debugger pauses the program, so the programmer can examine the state at that point and then step line by line.
  • Watch: a list of variables/expressions whose current values are displayed while paused, showing exactly when a value becomes wrong.

5. What is the purpose of a unit test? Write a unit test for a function square(n).

Model answer

A unit test checks that one small part of a program (a function) gives the expected output for given inputs, catching bugs early and preventing old features from breaking after changes.

def square(n):
    return n * n
assert square(3) == 9
assert square(-4) == 16
assert square(0) == 0
print("square() passed")

This lesson ends with a quiz of 8 MCQs. Open the lesson on PrepOasis to take it and save your progress.

Previous: 3.7 Connecting Python to a Database (SQLite) · Next: Unit 3 Review, Situational Quiz and Unit Test

All lessons in Computer Science XII (HSSC-II) – FBISE Complete SLO-Based Course