Skip to content

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:

python
squares = []
for i in range(10):
    squares.append(i * i)

Prompt:

"Refactor this code to use a Python List Comprehension."

Result:

python
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.

python
def c(x,y): return x+y
```"

Result:

python
def calculate_sum(first_number, second_number):
    return first_number + second_number

4. 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.

python
if user:
    if user.is_active:
        if user.has_permission:
            save()

Result:

python
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 map or 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 ValueError if the user types text instead of a number, and KeyboardInterrupt if they quit."

Debugging: The Detective πŸ•΅οΈβ€β™‚οΈ ​

When you see a traceback, don't panic.

The "Fix It" Workflow ​

  1. Copy the Error: Copy the entire traceback.
  2. Copy the Code: Copy the relevant function.
  3. The Prompt:

    "I am getting this IndexError on 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.

python
def add_item(item, list=[]):
    list.append(item)
    return list

Prompt:

"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=None instead."

Task: The "Spaghetti" Challenge 🍝 ​

Task

Take an old script you wrote (or find a bad example online).

  1. Ask AI to "Identify 3 smells in this code".
  2. Ask AI to "Refactor it".
  3. Compare the results. Did it break anything?

Common Beginner "Smells" πŸ‘ƒ ​

Ask AI to check your code for these specific issues:

  1. Global Variables:
    • Smell: Using global x inside functions.
    • Fix: Pass arguments and return values instead.
  2. The "Arrow" of Logic:
    • Smell: 5 levels of nested if statements.
    • Fix: Use "Early Returns" (e.g., if not valid: return).
  3. Magic Numbers:
    • Smell: if score > 75:.
    • Fix: PASSING_SCORE = 75 and if score > PASSING_SCORE:.

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 while loop runs forever. Add print() statements to this code that show the value of i and total at 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 the user_data dictionary 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, and total for each iteration."

python
total = 0
for i in range(3):
    total += i * 2

Result:

Iterationii * 2total (before)total (after)
10000
21202
32426

11. The "Off-by-One Detective" πŸ•΅οΈβ€β™€οΈ ​

Loop errors are classic.

Prompt:

"I am getting an IndexError in 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:

python
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:

python
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!

ErrorMeaningExample
SyntaxErrorYou broke the grammar rules.Missing a : after if.
IndentationErrorYour spacing is messy.Code inside def isn't indented.
NameErrorUsing a variable that doesn't exist.print(x) when x wasn't defined.
TypeErrorMixing incompatible types."Age: " + 25 (Cannot add text + number).
IndexErrorLooking for an item not in the list.list[10] when list has 3 items.
KeyErrorLooking 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?"