Refactoring & Debugging: The Rubber Duck 2.0 π¦π β
We've all heard of "Rubber Duck Debugging" (explaining your code to a toy duck to find the bug). AI is Rubber Duck 2.0. It talks back!
Refactoring: Cleaning the Kitchen π§Ή β
You wrote a script. It works, but it's messy. It's 200 lines of spaghetti. AI is excellent at cleaning up syntax and applying best practices (making it "Pythonic").
1. "Explain this code" (The Translator) β
Paste a complex function (maybe a Regular Expression) and ask for a translation.
Prompt:
"Explain this Regex pattern to me:
^[\w\.-]+@[\w\.-]+\.\w+$"
Result: It will explain that this matches an email address format.
2. "Pythonic" Refactoring β
Beginners often write C-style loops in Python. AI can teach you better ways.
Original Code:
squares = []
for i in range(10):
squares.append(i * i)Prompt:
"Refactor this code to use a Python List Comprehension."
Result:
squares = [i * i for i in range(10)]3. "Optimize for Readability" β
Prompt:
"Refactor this Python code to follow PEP-8 standards and use meaningful variable names.
pythondef c(x,y): return x+y ```"
Result:
def calculate_sum(first_number, second_number):
return first_number + second_number4. The "Name Giver" (Improving Variable Names) π·οΈ β
Beginners often use x, y, temp. AI helps you name things clearly.
Prompt:
"Rename variables in this code to be descriptive.
d = 86400->seconds_in_dayx = input()->user_selection"
5. The "Flattener" (De-nesting If Statements) π₯ β
Deeply nested code is hard to read.
Prompt:
Refactor this code to use 'Early Returns' and reduce nesting levels.
pythonif user: if user.is_active: if user.has_permission: save()
Result:
if not user or not user.is_active or not user.has_permission:
return
save()6. The "Speedrunner" (Loop Optimization) π β
Python loops can be slow. AI knows the fast tricks.
Prompt:
"This loop takes 10 seconds to run. Can you optimize it using
mapor built-in functions?"
Result: Replacing a manual sum loop with sum(list).
7. The "Safety Net" (Adding Error Handling) πΈοΈ β
Beginners often forget try/except.
Prompt:
"Add error handling to this input function. It should catch
ValueErrorif the user types text instead of a number, andKeyboardInterruptif they quit."
Debugging: The Detective π΅οΈββοΈ β
When you see a traceback, don't panic.
The "Fix It" Workflow β
- Copy the Error: Copy the entire traceback.
- Copy the Code: Copy the relevant function.
- The Prompt:
"I am getting this
IndexErroron line 5. Here is the code and the error. What is causing it and how do I fix it?"
Logic Bugs (The Silent Killers) β
Sometimes there is no error message, but the result is wrong.
Example: Mutable Default Arguments.
def add_item(item, list=[]):
list.append(item)
return listPrompt:
"I expect this function to return a new list each time, but it keeps adding to the old one. Why?"
AI Answer:
"In Python, default arguments are evaluated only once at definition time. You should use
list=Noneinstead."
Task: The "Spaghetti" Challenge π β
Task
Take an old script you wrote (or find a bad example online).
- Ask AI to "Identify 3 smells in this code".
- Ask AI to "Refactor it".
- Compare the results. Did it break anything?
Common Beginner "Smells" π β
Ask AI to check your code for these specific issues:
- Global Variables:
- Smell: Using
global xinside functions. - Fix: Pass arguments and return values instead.
- Smell: Using
- The "Arrow" of Logic:
- Smell: 5 levels of nested
ifstatements. - Fix: Use "Early Returns" (e.g.,
if not valid: return).
- Smell: 5 levels of nested
- Magic Numbers:
- Smell:
if score > 75:. - Fix:
PASSING_SCORE = 75andif score > PASSING_SCORE:.
- Smell:
8. The "Logger" (Adding Print Statements) π¨οΈ β
We all use print() to debug. AI can add them strategically for you.
Prompt:
"I can't figure out why this
whileloop runs forever. Addprint()statements to this code that show the value ofiandtotalat every step, so I can trace the logic."
9. The "Data Inspector" (Debugging Lists & Dicts) π β
Beginners often get IndexError or KeyError.
Prompt:
"I am getting
IndexError: list index out of range. Add a print statement before the error line to show the length of the list and the index I am trying to access."
Prompt:
"I am getting
KeyError: 'address'. Add a print statement to show all available keys in theuser_datadictionary before I try to access it."
10. The "Trace Table" Generator π β
If a loop is confusing, ask AI to "play computer" and create a table of values.
Prompt:
"Create a trace table for this loop. Show the values of
i,current_num, andtotalfor each iteration."pythontotal = 0 for i in range(3): total += i * 2
Result:
| Iteration | i | i * 2 | total (before) | total (after) |
|---|---|---|---|---|
| 1 | 0 | 0 | 0 | 0 |
| 2 | 1 | 2 | 0 | 2 |
| 3 | 2 | 4 | 2 | 6 |
11. The "Off-by-One Detective" π΅οΈββοΈ β
Loop errors are classic.
Prompt:
"I am getting an
IndexErrorin this loop:for i in range(len(my_list) + 1):. Explain why this is happening using a list of 3 items as an example."
Result: AI explains that range(4) goes 0, 1, 2, 3, but indices are 0, 1, 2. Index 3 causes the crash.
12. The "Function Extractor" (DRY Principle) β»οΈ β
If you copy-paste code twice, you need a function.
Original Code:
print("Welcome to the game!")
print("Loading...")
# ... later ...
print("Welcome to the game!")
print("Loading...")Prompt:
"I use these print statements multiple times. Refactor this into a reusable function called
show_header."
Result:
def show_header():
print("Welcome to the game!")
print("Loading...")
show_header()
# ... later ...
show_header()Cheat Sheet: Common Python Errors π β
Ask AI to explain these when you see them!
| Error | Meaning | Example |
|---|---|---|
SyntaxError | You broke the grammar rules. | Missing a : after if. |
IndentationError | Your spacing is messy. | Code inside def isn't indented. |
NameError | Using a variable that doesn't exist. | print(x) when x wasn't defined. |
TypeError | Mixing incompatible types. | "Age: " + 25 (Cannot add text + number). |
IndexError | Looking for an item not in the list. | list[10] when list has 3 items. |
KeyError | Looking for a key not in the dictionary. | dict['name'] when key is missing. |
Warning: The "Yes Man" π€₯ β
The AI wants to please you. If you ask "Is this code correct?", it might say "Yes!" even if it's flawed. Better Question: "What are the potential edge cases where this code might fail?"
Related Topics π β
- Technical Debt: Why bad code slows you down (The Dirty Kitchen).
- Python Control Flow: Master loops and logic to spot bugs faster.