Debugging Code Automatically with AI — Guided Lab
Welcome to the Lab 🛠️
Debugging can be tedious, but AI can act as your personal code inspector, spotting errors, suggesting fixes, and explaining why something went wrong. In this session, you’ll learn how to turn broken code and error messages into working solutions using AI.
Step 0: Identify the Problem
You wrote this function to check if a number is prime:
def is_prime(n):
for i in range(2, n):
if n % i == 0:
return False
return True
Run it with is_prime(1) — notice the function incorrectly returns True. Your goal: debug this function using AI to handle all edge cases correctly.
Step 1: Craft a Debugging Prompt
Include:
- The current code
- A clear description of the problem
- Desired behavior
Prompt Example:
Here is my Python function:
def is_prime(n):
for i in range(2, n):
if n % i == 0:
return False
return True
It incorrectly returns True for n = 1. Please fix the function so it handles n <= 1 correctly and explain the changes.
Step 2: AI Output Example
def is_prime(n):
"""Check if a number is prime."""
if n <= 1:
return False
for i in range(2, n):
if n % i == 0:
return False
return True
AI Explanation:
Added a check for
n <= 1because 1 and negative numbers are not prime.
Step 3: Test the Fixed Function
print(is_prime(1)) # False
print(is_prime(2)) # True
print(is_prime(9)) # False
The function now works perfectly. If it didn’t, consider refining your prompt with more explicit instructions or edge cases.
Step 4: Optimize & Refine
AI can also help improve efficiency. Prompt example:
Optimize this is_prime function for large n. Keep it correct for all edge cases.
AI might suggest:
- Loop only up to
sqrt(n)instead ofn-1 - Skip even numbers after 2
Optimized Function Example:
def is_prime(n):
if n <= 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
for i in range(3, int(n**0.5)+1, 2):
if n % i == 0:
return False
return True
Step 5: Mini Lab Challenges
- Debug a function
reverse_string(s)that fails on empty strings. - Fix a
fibonacci(n)function that returns incorrect values forn=0orn=1. - Ask AI to explain each line of a fixed function.
- Optimize a function with a runtime constraint — compare AI’s suggestions.
Step 6: Pro Tips
- Always include the current code in your prompt — AI needs context.
- Clearly describe errors or undesired behavior.
- Ask AI for explanations, not just fixes, to enhance learning.
- Include edge cases to make code robust.
- Iteratively improve the prompt for better readability, correctness, and performance.
Lab Summary
- AI is your debugging assistant, guiding you through logical errors.
- Effective prompts = code + problem description + desired outcome.
- Iteration is key: test AI suggestions, refine prompts, and retest.
- Debugging with AI saves time, reinforces learning, and improves coding confidence.


