Python for AI: where to start
A practical guide to learning Python for AI apps: setup, the basics you need, and your first call to a free local model.

In 30 seconds
- Python is the most common language for AI applications, and libraries such as LangChain and LangGraph are built for it.
- You don't need the whole language before you build. Learn six basics, then start a small project.
- Everything here is free, and the model runs on your computer.
1. Set up your machine
Install Python 3.10 or newer from python.org, then create a virtual environment for each project so libraries don't mix:
python -m venv .venv
# Windows
.venv\Scripts\activate
# macOS / Linux
source .venv/bin/activate
2. The six basics
| Basic | Why you need it for AI |
|---|---|
| Variables and types | Holding text, numbers and results |
| Lists and dicts | Model messages and replies use this shape |
| Functions | The tools an agent calls are functions |
| Dataclasses | Organised data instead of loose dicts |
| Type hints | Libraries read them to understand your inputs |
| try / except | The model or network can fail at any moment |
3. One example with them
from dataclasses import dataclass
@dataclass
class Task:
title: str
hours: float
done: bool = False
def remaining_hours(tasks: list[Task]) -> float:
return sum(task.hours for task in tasks if not task.done)
tasks = [Task("Read the docs", 1.5, done=True), Task("Build the API", 4), Task("Write tests", 2)]
print(f"Remaining: {remaining_hours(tasks)} hours")
print([task.title for task in tasks if not task.done])
Output:
Remaining: 6 hours
['Build the API', 'Write tests']
4. Your first local model call
Install Ollama, download a small model (about 2 GB) and install the library:
ollama pull qwen2.5:3b
pip install ollama
from ollama import chat
def ask(question: str) -> str:
response = chat(
model="qwen2.5:3b",
messages=[{"role": "user", "content": question}],
)
return response.message.content
try:
print(ask("Explain what an API is in one sentence."))
except ConnectionError:
print("Ollama is not running. Start it, then try again.")
No API key, no bank card, and your data stays on your computer.
Common mistakes
- Installing without a virtual environment, so versions clash between projects.
- Watching courses without writing code. Change every example and see what breaks.
- Copying code you don't understand from an assistant. Ask it to explain line by line.
A two-week practice plan
- Days 1 to 4: variables, lists, dicts and functions.
- Days 5 to 7: files, JSON and error handling.
- Days 8 to 10: classes and type hints.
- Days 11 to 14: a script that asks a local model about a file and saves the answer.
Next guide
Code tested on 30 November 2026 with Python 3.10, LangChain 1.4 and LangGraph 1.2.