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 earlyreturn. - 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.
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.
A quick 3-question quiz on this lesson — instant feedback.
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.
Project-based Coding with AI: ChatGPT & Claude courses if you want a structured paid path after the free lessons. Wait for a sale — prices drop often.
Browse on Udemy →Search Amazon for Coding with AI: ChatGPT & Claude books — check the publication year so the examples match current versions.
Search Amazon →