Getting Started with Python for AI
In short: Set up a verified Python 3.10+ interpreter and an isolated venv, and install packages with python -m pip so the SDK you import is the one you installed.
Why This Matters
Every agent you build in this course — from the "Hello World" agent in Lesson 4 to the multi-tool autonomous systems later on — will be a Python program. Python is the default language of the AI ecosystem: Anthropic's official SDK (anthropic), the data tooling, the agent frameworks, and virtually every code example you will find in documentation are Python-first. Before you can send a single message to Claude, you need a working Python environment, and you need to be able to trust it: the right Python version, an isolated place to install packages, and the ability to run a script and know exactly which interpreter executed it.
That last point matters more than it sounds. The single most common reason a beginner's first API call fails has nothing to do with the API — it is an environment problem: the package was installed into one Python while the script ran under another. This lesson exists so that never happens to you.
Core Concepts
1. Which Python?
The anthropic SDK and this course's examples assume Python 3.10 or newer. Check what you have from a terminal:
python --version
Python 3.12.4
On Windows, if python is not found (or opens the Microsoft Store), try the launcher py --version. On macOS/Linux, python3 --version is often the reliable spelling. Whatever command prints a 3.10+ version is your Python command — use that same spelling consistently for everything below.
Inside Python, the version lives in sys.version_info, a tuple-like object you can compare directly:
import sys
print(sys.version_info[:3]) # e.g. (3, 12, 4)
print(sys.version_info >= (3, 10)) # True on any supported version
Note that comparison is done on the tuple, not the string. "3.9" > "3.10" is True in Python because strings compare character by character — a classic trap we will revisit in the pitfalls section.
2. Virtual Environments: One Sandbox Per Project
A virtual environment (venv) is a private, per-project copy of Python's package area. Installing a package inside a venv affects only that project. Without one, every project on your machine shares a single global package pool — and the day project A needs anthropic v0.40 while project B needs something incompatible, both break.
Create and activate one in your project folder:
python -m venv .venv
# Windows (PowerShell)
.venv\Scripts\Activate.ps1
# macOS / Linux
source .venv/bin/activate
When the venv is active, your prompt gains a (.venv) prefix, and python now refers to the venv's interpreter. Deactivate any time with deactivate. The .venv folder is disposable — never commit it to git; you can always recreate it.
3. Installing Packages with pip
pip is Python's package installer. The safest way to invoke it is through the interpreter you intend to use:
python -m pip install anthropic
Why python -m pip instead of bare pip? Because pip on your PATH can belong to a different Python installation than python does. python -m pip removes all doubt: it runs the pip module of exactly that interpreter.
Verify the installation and record your dependencies:
python -m pip show anthropic # version + install location
python -m pip freeze > requirements.txt
A requirements.txt lets anyone (including future you) rebuild the environment with python -m pip install -r requirements.txt.
4. Running Python: REPL vs Scripts
You will use two modes constantly:
- The REPL (
pythonwith no arguments) — an interactive prompt for quick experiments. Type an expression, see the result immediately. Exit withexit()or Ctrl-Z/Ctrl-D. - Scripts (
python my_script.py) — files you run top to bottom. All real agent code lives in scripts.
A minimal script, hello.py:
model = "claude-sonnet-4-6"
max_tokens = 500
message = f"Ready to call {model} with up to {max_tokens} tokens."
print(message)
Ready to call claude-sonnet-4-6 with up to 500 tokens.
The f"..." syntax is an f-string: anything inside {} is evaluated and inserted into the string. You will use f-strings constantly to build prompts for Claude, so get comfortable with them now.
Worked Example: An Environment Self-Check Script
Let's put all of this together into a genuinely useful script — one that inspects your setup and reports whether you are ready for the rest of the module. Save this as check_env.py and run it with python check_env.py:
import sys
def check_python_version(minimum=(3, 10)):
"""Return (ok, detail) for the running interpreter."""
current = sys.version_info[:3]
ok = sys.version_info >= minimum
detail = f"Python {current[0]}.{current[1]}.{current[2]}"
return ok, detail
def check_package(package_name):
"""Return (ok, detail) for an importable package."""
try:
__import__(package_name)
return True, f"package '{package_name}' is importable"
except ImportError:
return False, f"package '{package_name}' is NOT installed"
def main():
checks = [
check_python_version(),
check_package("anthropic"),
]
for ok, detail in checks:
status = "PASS" if ok else "FAIL"
print(f"[{status}] {detail}")
if all(ok for ok, _ in checks):
print("Environment ready. On to the API key!")
else:
print("Fix the FAIL lines above before continuing.")
if __name__ == "__main__":
main()
On a correctly configured machine the output looks like:
[PASS] Python 3.12.4
[PASS] package 'anthropic' is importable
Environment ready. On to the API key!
If you have not yet installed the SDK, you will instead see [FAIL] package 'anthropic' is NOT installed — and now you know exactly what to fix and how (python -m pip install anthropic, inside your activated venv).
Read the script again and notice the patterns: functions that return results instead of printing directly, tuples used to bundle a status with a message, a main() guard so the file can also be imported without side effects. These are habits you will reuse in every agent you write.
Common Pitfalls
- Comparing version strings instead of tuples.
sys.version >= "3.10"is wrong:sys.versionis a string, and"3.9..." >= "3.10"evaluatesTruebecause"9" > "1"character-wise. Always comparesys.version_info >= (3, 10). pip installsucceeded butimportfails. Almost always means pip installed into a different interpreter than the one running your script — typically because the venv was not activated, or barepippointed elsewhere. Cure: activate the venv and usepython -m pip install ....- Forgetting to activate the venv in a new terminal. Activation is per-terminal-session. Every new window starts deactivated; the
(.venv)prefix in your prompt is your visual confirmation. - Shadowing a package with your own file name. If you name a script
anthropic.py, thenimport anthropicimports your file, not the SDK, and you get bafflingAttributeErrors. Never name a script after a package you import. - Windows-specific:
pythonopens the Microsoft Store. Disable the "App execution alias" for Python in Windows settings, or use thepylauncher.
Summary
You now have the foundation every later lesson stands on: a verified Python 3.10+ interpreter, an isolated virtual environment, the anthropic SDK installed with python -m pip, and a self-check script that proves it all works. You also met the two idioms you will use most — f-strings for building text and sys.version_info tuple comparisons for guards.
The exercises that follow test exactly these skills: predicting f-string output, explaining why venvs exist, diagnosing the "pip installed it but import fails" mismatch, and extending the check_env.py self-check pattern into a fuller readiness report. Everything you need is on this page.
