Debugging Example – Finding the Maximum in a List
Below is a Python script that is supposed to find the maximum value in a list of numbers.
However, it contains a bug (or maybe a couple of bugs).
Your task is to run this code, observe what goes wrong, and fix the issues step by step.
def find_maximum(values):
max_val = 0
for val in values:
if val > max_val:
max_val = val
return val # Bug likely here
nums = [4, 1, 9, 3]
print("Max of", nums, ":", find_maximum(nums))
empty_list = []
print("Max of empty list:", find_maximum(empty_list))
Step 1 – Observe the Error
Running the script produces:
Max of [4, 1, 9, 3] : 3
Traceback (most recent call last):
File "buggy_script.py", line 8, in <module>
print("Max of empty list:", find_maximum(empty_list))
File "buggy_script.py", line 5, in find_maximum
return val
UnboundLocalError: local variable 'val' referenced before assignment
Observation:
-
The first list returns
3instead of9(logic problem). -
An
UnboundLocalErroroccurs when calling with an empty list.
Step 2 – Investigate the Logic for Non-Empty List
-
The loop correctly updates
max_valwhen a larger value is found. -
But at the end, the function returns
val, which is just the last loop value, not the maximum. -
For
[4, 1, 9, 3], the loop ends withval = 3, so it returns3.
Step 3 – Understand the Empty List Issue
-
For
[], the loop never runs. -
valis never assigned, soreturn valfails withUnboundLocalError. -
Even if we returned
max_valinstead, startingmax_val = 0could be wrong if all values are negative.
Step 4 – Fix the Bugs
-
Return
max_valinstead ofval. -
Handle empty list by raising an exception.
-
Initialize
max_valwith the first element of the list to handle negative numbers.
Revised Function:
def find_maximum(values):
if len(values) == 0:
raise ValueError("Cannot find max of an empty list")
max_val = values[0]
for val in values:
if val > max_val:
max_val = val
return max_val
Step 5 – Testing the Fix
nums = [4, 1, 9, 3]
print("Max of", nums, ":", find_maximum(nums))
empty_list = []
try:
print("Max of empty list:", find_maximum(empty_list))
except ValueError as e:
print("Error:", e)
Expected Output:
Max of [4, 1, 9, 3] : 9
Error: Cannot find max of an empty list
Step 6 – Reflection
-
Bug #1: Returned the wrong variable (
valinstead ofmax_val). -
Bug #2: No handling for empty input.
-
Fixing logic and adding input validation makes the function more robust.
-
This debugging process involved:
-
Observing the traceback.
-
Checking variable states.
-
Updating logic to avoid hidden edge case failures.
-
