Practical Exercise 4
Hands-On
Use AI to identify, understand, and fix bugs efficiently
2026 WayUp
1
Use AI to analyze error messages and stack traces
2
Apply chain-of-thought debugging prompts
3
Debug logic errors with AI assistance
4
Write tests to prevent regression
class ShoppingCart:
def __init__(self):
self.items = []
def add_item(self, name, price, quantity):
self.items.append({"name": name, "price": price, "qty": quantity})
def remove_item(self, name):
for item in self.items:
if item["name"] == name:
self.items.remove(item) # Bug 1: Modifying list while iterating
def calculate_total(self):
total = 0
for item in self.items:
total += item["price"] * item["quantity"] # Bug 2: Wrong key name
return total
def apply_discount(self, percent):
self.total = self.calculate_total()
return self.total - (self.total * percent) # Bug 3: percent should be /100
Traceback (most recent call last):
File "cart.py", line 42, in <module>
total = cart.calculate_total()
File "cart.py", line 15, in calculate_total
total += item["price"] * item["quantity"]
KeyError: 'quantity'
def find_duplicates(lst):
"""Return list of duplicate values."""
seen = []
duplicates = []
for item in lst:
if item in seen:
duplicates.append(item) # Bug: adds multiple times
seen.append(item)
return duplicates
# find_duplicates([1, 2, 2, 2, 3]) returns [2, 2] instead of [2]
Ask AI: "Trace through find_duplicates([1, 2, 2, 2, 3]) step by step. Show the state of 'seen' and 'duplicates' after each iteration."
async def fetch_user_data(user_ids):
results = []
for user_id in user_ids:
data = await fetch_user(user_id)
results.append(data) # Potential: Order not guaranteed with concurrent calls
return results
async def update_balance(user_id, amount):
balance = await get_balance(user_id)
new_balance = balance + amount # Bug: Race condition between read and write
await set_balance(user_id, new_balance)
You've mastered AI-assisted debugging
Next: Practical 5 - AI-Assisted Code Review
2026 WayUp - way-up.io