BeginnerCoder

Lesson 11 — Refactor AI code for readability

Same behaviour, better shape

AI code often works but is hard to read: one-letter names, deep nesting, magic numbers. You will maintain this code, so make it readable. That is refactoring: changing the shape of code without changing what it does.

Typical moves:

  • Good names: g(s) → letter_grade(score).
  • Flatten nesting: else: if ... → elif ..., or an early return.
  • Data instead of branches: a table of thresholds and a loop instead of five ifs.
SIZES = [(1000, "large"), (100, "medium")]
for limit, label in SIZES:
    if amount >= limit:
        return label

How do you know you did not change the behaviour? Compare old and new on many inputs. Here we check every score from 0 to 100.

Why it matters: readable code is code you (and your teammates) can still fix in six months. Tests make refactoring safe.

Want it another way?
Task

Write letter_grade(score) using the GRADES table and a loop (return "F" if nothing matches). It must give the same result as g() for every score 0–100.

Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.

← Back
Next →
Test your knowledge

A quick 3-question quiz on this lesson — instant feedback.

Enjoying this lesson? Share it.

Keep going with Coding with AI: ChatGPT & Claude

Ready for more? Optional paid resources that pick up where this lesson leaves off.

Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.