This fictional example shows how a tutor walks through a bug with a student. The student's task: write a function that returns the average mark from a list, and returns zero for an empty list.
The student's code, written in plain words:
- Line 1: define a function called average that takes a list called marks.
- Line 2: set total to 0.
- Line 3: for each index i in range(1, len(marks)), add marks[i] to total.
- Line 4: return total divided by len(marks).
The symptom: for the list 60, 70, 80 the function returns 50.0 instead of 70.0, and for an empty list the program crashes with ZeroDivisionError.
Step 1, trace with a small input. The tutor asks the student to write down the value of i on each pass. The loop runs with i = 1 and i = 2 only, so total is 70 + 80 = 150, and 150 divided by 3 is 50.0. The first mark is never added, because range(1, n) starts at 1 and Python lists start at index 0.
Step 2, fix the cause, not the symptom. The student changes the loop to start at 0, or better, loops directly over the items with "for mark in marks", which removes the index error entirely.
Step 3, handle the edge case the brief named. An empty list makes len(marks) equal 0, so the division fails. The student adds a check at the top: if the list is empty, return 0.
Step 4, test. The student tries 60, 70, 80 (expects 70.0), a single mark of 55 (expects 55.0) and an empty list (expects 0). All three pass.
The lesson the student keeps is a habit, not a fix: trace with a tiny input, compare each value with what you expected, and test the edge cases written in the brief. Our Python for beginners guide covers the same habits from the start.