BeginnerCoder

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.

  1. Split the text into parts: "2 + 3".split() → ["2", "+", "3"].
  2. Exactly 3 parts? Is the middle one a known operator?
  3. Can both sides be turned into numbers with float()? (try/except ValueError.)
  4. 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.

Want it another way?
Task

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.

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