Lesson 12 — Security: AI code that trusts input
Never run what the user typed
Ask for "a calculator that takes the user's text" and an assistant may answer with one line: eval(text). It works for 2 + 3… and also runs any Python code the user types. On a server, that means a stranger can read your files or delete data. This is called code injection.
The fix is an allow-list: accept only the exact shape you expect and reject everything else.
- Split the text into parts:
"2 + 3".split()→["2", "+", "3"]. - Exactly 3 parts? Is the middle one a known operator?
- Can both sides be turned into numbers with
float()? (try/except ValueError.) - Special cases: division by zero.
Anything that fails a check returns "rejected". Do not try to block "bad words" — attackers find new ones. Allow only what is good.
Why it matters: assistants write code that works for the happy path. Thinking about the attacker's input is your job.
Replace eval in safe_calculate() with the allow-list from the theory: "a op b" with + - * /, numbers via float(), and "rejected" for anything else (including division by zero).
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 →