Python for AI work
Write a small Python program that rejects invalid input.
In this lesson · 01 of 10
All lessons in this track →Saved in this browser. View your learning.
Start with the idea
Write a small Python program that rejects invalid input.
Start with a clear rule for valid input. Test a valid case and cases that must fail. A program should not hide an error by returning a normal-looking answer.
Input validation: Checking input against the rules before using it.
See the example and check your understanding
A made-up teaching example
The greeter accepts nonempty text with a 100-character limit. A 101-character input must fail. Put the length check after the blank-input check and test both failures.
Ask yourself
Should every exception be turned into a successful greeting?
Show the explanation
No. Keep invalid input visibly different from success. Record the run command and Python version, or label a paper trace as unexecuted.
Start with these checks
- Test the limit and the case beyond it.
- Keep errors distinct from normal output.
- Record how you ran the program.
Use the different practice case below and check every requirement in its full instructions.
The video explains the main idea. Use the sources, instructions and checks below to complete the practice.
Captions appear here during playback.
Python for AI work
Write a small Python program that rejects invalid input.
Video playback is unavailable. Read the descriptive transcript below, go directly to practice, or open the video file.
Source-based teaching example · Fictional data · Reviewed 2026-10-03. Microsoft Mark · locally synthesized. On a small screen, use fullscreen for diagram details or read the transcript.
Read the descriptive transcript
0:00 · What you will learn
Write a small Python program that rejects invalid input.
What appears on screen
Write a small Python program that rejects invalid input.
0:06 · The idea
Start with a clear rule for valid input. Test a valid case and cases that must fail. A program should not hide an error by returning a normal-looking answer.
What appears on screen
Start with a clear rule for valid input. Test a valid case and cases that must fail. A program should not hide an error by returning a normal-looking answer.
0:19 · One useful term
Input validation. Checking input against the rules before using it.
What appears on screen
Checking input against the rules before using it.
0:27 · A worked example
The greeter accepts nonempty text with a 100-character limit. A 101-character input must fail. Put the length check after the blank-input check and test both failures.
What appears on screen
The greeter accepts nonempty text with a 100-character limit. A 101-character input must fail. Put the length check after the blank-input check and test both failures.
0:42 · Your turn to think
Should every exception be turned into a successful greeting? Pause and decide before continuing.
What appears on screen
Should every exception be turned into a successful greeting? Pause the video if you need more time.
0:58 · Why this answer works
No. Keep invalid input visibly different from success. Record the run command and Python version, or label a paper trace as unexecuted.
What appears on screen
No. Keep invalid input visibly different from success. Record the run command and Python version, or label a paper trace as unexecuted.
1:11 · Check 1
Test the limit and the case beyond it.
What appears on screen
Test the limit and the case beyond it.
1:16 · Check 2
Keep errors distinct from normal output.
What appears on screen
Keep errors distinct from normal output.
1:22 · Check 3
Record how you ran the program.
What appears on screen
Record how you ran the program.
1:27 · Now try a different case
Open the lesson and try its different practice case. Use every check in the full task. Watching alone does not mark the lesson complete.
What appears on screen
Open the lesson Try the new case Check and revise The full task and its requirements are in the linked lesson.
Watching explains the example. Complete the lesson practice to check what you can do. Explore all visual lessons →
Lesson preparation and outcomes
Prerequisites: Basic file editing; no API account.
By the end, you can: Trace a function, validate its inputs and return a typed error before any optional provider call.
Worked scenario and practice feedback
The offline greeter accepts a nonempty string. A new 101-character input must fail a declared 100-character cap. Check length after the blank-input guard; do not catch every exception and turn it into an apparently successful message.
Guided and independent practice: Predict outcomes for 0/1/100/101 characters, run the assertions, then independently add a non-string input.
Answer criteria: No invalid input produces normal output; exact run command and interpreter version recorded. If the local pack or interpreter is unavailable, trace the synthetic input, expected output and failure guard on paper; label execution unverified. Required practice uses no paid API calls, accounts, purchase, operational data or actual deployment.
Foundations made you AI-literate. Intermediate makes you AI-capable. The split between the two is a programming language, a testable application contract, and the willingness to read a stack trace. We start with Python.
Three honest disclaimers up front:
- You will not become a software engineer from this lesson. You will learn enough Python to make AI do useful work for you.
- We will skip a lot of “real CS.” No object-oriented theory. No data structures lecture. No Big-O. You can come back to those later if you decide to.
- The first time you write code, things will break. That is the work. Reading error messages and fixing them is half the skill of programming.
Part 1 Set up a clean Python environment.
If you already have Python and a virtual environment habit, skip this point. If you don’t, do this exactly.
Install Python
Go to python.org/downloads. Install the latest stable version (3.12 or newer is fine). On Windows, check the “Add Python to PATH” box during install. On macOS, the python.org installer is preferred over Homebrew for a clean default.
Verify in a terminal:
python --version
# Python 3.12.xIf you see python: command not found, your PATH isn’t set. Fix that before continuing.
Make a project folder + venv
A virtual environment provides a project-specific interpreter/package environment; it is not an operating-system security sandbox. It isolates installed packages but does not automatically pin versions, trust dependencies or block network access.
mkdir sd-tier02
cd sd-tier02
python -m venv .venv
# Activate (Mac/Linux):
source .venv/bin/activate
# Activate (Windows PowerShell):
.venv\Scripts\Activate.ps1You’ll see (.venv) prepended to your shell prompt. That’s the signal that the venv is active. Every time you open a new terminal in this project, activate the venv again.
Part 2 The Python you'll actually use.
These are the constructs that show up in 90% of AI code. Burn them in.
Variables and types
name = "operator" # string
score = 42 # integer
pi = 3.14159 # float
done = True # boolean
empty = None # nothingPython figures out the type from the value. No declarations.
Strings (and f-strings, the most useful syntax in the language)
who = "Operator"
greeting = f"Welcome back, {who}. You have {3} reps left."
# 'Welcome back, Operator. You have 3 reps left.'The f prefix lets you embed expressions in { }. Every prompt-template you build will use this.
Lists, dicts, and how to access them
roles = ["medic", "comms", "logistics"]
roles[0] # 'medic'
roles.append("intel") # adds to end
config = {"model": "claude-haiku-4-5", "max_tokens": 1024}
config["model"] # 'claude-haiku-4-5'
config["temperature"] = 0.2A list is ordered, accessed by index. A dict is a key→value map. Parsed JSON object payloads commonly become dictionaries. An SDK may instead return a typed response object accessed through attributes or its documented serialization method; inspect the actual interface before indexing it.
Loops
for r in roles:
print(r)
for key, value in config.items():
print(f"{key} = {value}")Conditionals
if score >= 90:
print("strong")
elif score >= 70:
print("ok")
else:
print("rework")Functions
def summarize(text: str, max_words: int = 100) -> str:
"""Return a one-paragraph summary of the input."""
# ... call AI here ...
return "..."
result = summarize("Long text here.", max_words=50)Type hints (str, int, -> str) are optional but encouraged. They’re documentation that the editor reads.
Try / except (read errors, don’t fear them)
try:
response = call_the_api(prompt)
except TimeoutError:
response = "API timed out. Try again."
except Exception as e:
response = f"Something else went wrong: {e}"You will see exceptions constantly. Reading them is the skill. The last line of a Python error message tells you what broke.
That’s the Python you need. Bookmark this section, come back to it.
Part 3 Packages: pip, requirements, dotenv.
Python’s standard library is rich, but the AI stack you’ll use lives in third-party packages. Installing them is one command.
Install with pip
pip install anthropic openai python-dotenvpip is the package manager. You install once per venv. The packages drop into .venv/lib/....
Pin your dependencies
Write a requirements.txt:
anthropic==0.40.0
openai==1.55.0
python-dotenv==1.0.1Anyone who clones your project runs pip install -r requirements.txt and requests the specified package versions; runtime, platform and transitive dependency resolution still affect reproducibility. Those version numbers are illustrative — they’ll be stale by the time you read this, so after you pip install, run pip freeze and pin whatever it actually shows. Version drift is a real source of bugs in AI work. Pin your versions.
Keep your API key out of code
Never paste your API key into a file you commit. Use a .env file at the project root:
ANTHROPIC_API_KEY=sk-ant-...your-key-here...
OPENAI_API_KEY=sk-...your-key-here...Add .env to your .gitignore immediately. Then load it in code:
from dotenv import load_dotenv
import os
load_dotenv()
api_key = os.getenv("ANTHROPIC_API_KEY")This pattern shows up in every AI codebase. It’s worth burning in.
Part 4 Run a complete offline input/result boundary.
Start with a standard-library script that returns a synthetic result. This teaches the same input/function/result boundary without a credential, network request, account, or charge. Save as hello.py and run python hello.py.
import json
def generate(prompt):
if not isinstance(prompt, str) or not prompt.strip():
return {"status": "error", "text": None, "error": "empty_input"}
return {"status": "complete", "text": "Hello, learner.",
"error": None, "usage": None, "request_id": "synthetic-01"}
result = generate("Greet the learner.")
assert result["status"] == "complete"
assert generate(" ")["error"] == "empty_input"
print(json.dumps(result))A mock proves that your Python wiring works. It does not measure a model’s quality, latency, billing or availability. Lesson 02 explains the optional provider boundary, including complete, incomplete, refusal and error responses. Keep secrets out of source, printed exceptions and logs. A .env exclusion is useful but does not remove secrets from earlier Git history.
The earlier package and key patterns are reference instruction. The required drill uses no external packages or real API. If later authorized to use a provider, verify the exact SDK, model ID, supported parameters, account access and data policy in its official documentation; do not silently replace a missing model with another.
Interface/reference limits
Use the workflow reference to distinguish model capability, deployment and harness controls. Provider snippets in this lesson are illustrative, have not been executed against an actual provider in this revision, and require current SDK/model capability verification before separately authorized use.