Chapter 4A Gentle Programming Refresher for AI Builders
You do not need to be an expert programmer to build agents, but you do need to be comfortable reading and adapting a small amount of code. This chapter refreshes exactly that — the handful of Python ideas that appear again and again in the rest of the book, plus a glance at JavaScript so it never looks foreign. If you have programmed before, treat this as a warm-up. If you are new or rusty, go slowly and type every example yourself, because code, like a musical instrument, is learned by playing rather than by watching.
How Much Programming Do You Really Need?
Here is the reassuring truth: in AI work you will spend far more time reading, adapting, and running code that others wrote than building anything from scratch. You do not need to master all of Python. You need fluency in perhaps a fifth of it — the core that does most of the work — and that fifth is what this chapter covers. Everything here will reappear in later chapters, so time spent now pays off many times over.
Variables and Basic Types
A variable is simply a named box that holds a value, so you can refer to it later by name. Python has a few basic kinds of value — called types — that you will use constantly: text (strings), whole numbers (integers), decimals (floats), and true/false values (booleans).
name = "Ada" # a string (text, in quotes)
age = 36 # an integer (whole number)
price = 19.99 # a float (decimal number)
is_ready = True # a boolean (True or False)When you want to build a sentence out of variables, the cleanest tool is an f-string: put the letter f just before the opening quote, and drop any variable inside curly braces.
greeting = f"Hello, {name}. You are {age} years old."
print(greeting) # Hello, Ada. You are 36 years old.Lists and Dictionaries: The Two Workhorses
Two structures show up everywhere in AI code, so it is worth knowing them cold. Almost everything you build will be made of these two pieces.
Lists: ordered collections
A list holds many values in order, written inside square brackets. You can read items by their position, add new ones, and ask how many there are.
models = ["small", "medium", "large"]
print(models[0]) # "small" -- counting starts at 0!
models.append("huge") # add a new item to the end
print(len(models)) # 4 -- how many itemsDictionaries: labelled values
A dictionary stores values under named keys, written in curly braces as key: value pairs. Think of a row of labelled drawers: instead of reaching for "position 2," you reach for the drawer labelled "name."
person = {"name": "Ada", "role": "engineer"}
print(person["name"]) # "Ada" -- look up by key
person["age"] = 36 # add a new key and valueHold this thought: nearly every message you send to a language model is a dictionary, and a whole conversation is a list of those dictionaries. We will return to that pattern at the end of the chapter, and it will look completely natural by then.
Making Decisions with if
An if statement lets your code choose what to do based on a condition. You can chain alternatives with elif ("else, if") and provide a fallback with else.
temperature = 0.9
if temperature > 0.7:
print("Creative and varied responses")
elif temperature > 0.3:
print("Balanced responses")
else:
print("Focused, predictable responses")Repeating Work with Loops
A for loop runs the same block of code once for each item in a list. This is the workhorse of AI projects, where you constantly process many documents, chunks, or messages in turn.
documents = ["doc one", "doc two", "doc three"]
for doc in documents:
print(f"Processing: {doc}")You have already seen this pattern at work: in Chapter 36 we looped over chunks to create an embedding for each one. That was this exact idea, applied to a real task.
Functions: Packaging Reusable Work
A function is a named, reusable block of code. You define it once with def, give it inputs called parameters, and it can hand back a result with return. Functions keep your code tidy and let you reuse logic instead of copying it from place to place.
def average(numbers):
if len(numbers) == 0:
return 0 # handle the empty case safely
return sum(numbers) / len(numbers)
print(average([10, 20, 30])) # 20.0The embed() and retrieve() helpers you met in the RAG chapter were functions exactly like this one. Now the words def, parameter, and return carry their full meaning for you.
Importing Libraries
As we saw in Chapter 3, a library is pre-written code that you install once and then bring into your program with import. This is how you reach the powerful tools that do the heavy lifting, instead of writing everything yourself.
import os # bring in a whole built-in library
from anthropic import Anthropic # bring in one piece of an installed library
client = Anthropic()Plain import X brings in the whole library X; the form from X import Y brings in just the single piece Y you need. You will use both throughout the book.
Working with Files
Reading text from a file is a common first step — for example, loading the documents that feed a RAG system. The with pattern below opens a file and safely closes it again when you are done.
with open("notes.txt") as f:
text = f.read()
print(text[:100]) # print just the first 100 charactersHere f.read() hands you the entire contents of the file as one string, and text[:100] takes a slice — the first hundred characters — which is a handy way to peek at large content without printing all of it.
The Shape of AI Code: Lists of Dictionaries
Now for the payoff that ties this whole chapter together. Almost every conversation with a model is represented as a list of dictionaries, where each dictionary is a single message with a role and some content. You have glimpsed this in earlier chapters; with the pieces from this one, you can now read it fluently.
messages = [
{"role": "user", "content": "Hello!"},
{"role": "assistant", "content": "Hi! How can I help?"},
{"role": "user", "content": "Explain agents simply."},
]
for message in messages:
print(f"{message['role']}: {message['content']}")Read it slowly and watch four ideas combine. messages is a list (square brackets). Each item is a dictionary (curly braces) with two keys, role and content. The for loop visits each message in turn, and the f-string pulls out its pieces to print. Lists, dictionaries, loops, and f-strings — every core idea from this chapter, working together. This single structure sits underneath nearly everything you will build, so recognizing it on sight is a genuine milestone.
A Word of JavaScript
This book is mostly Python, but you will occasionally meet a little JavaScript — and the encouraging news is that the concepts are identical. Only the spelling changes. Here are the same ideas, side by side.
const name = "Ada"; // a variable
const models = ["small", "large"]; // an array (Python calls it a list)
function average(numbers) { // a function
if (numbers.length === 0) return 0;
const total = numbers.reduce((a, b) => a + b, 0);
return total / numbers.length;
}
const messages = [ // an array of objects
{ role: "user", content: "Hello!" },
];Notice the family resemblance. JavaScript uses const to name a variable, leans on curly braces and parentheses where Python uses colons and indentation, and calls lists "arrays" and dictionaries "objects." If you can read the Python in this chapter, you can squint and read the JavaScript too — which is all the JavaScript fluency this book asks of you.
Summary
You refreshed the small core of Python that this book relies on: variables and their basic types, the two workhorse structures (lists and dictionaries), making decisions with if, repeating work with for loops, packaging logic into functions, importing libraries, reading files, and — most importantly — the "list of dictionaries" shape that underlies almost every conversation with a model. You also saw that JavaScript expresses the very same ideas with different punctuation. You do not need to have memorized any of this; you need only to recognize it when it appears, and that recognition will deepen with every chapter you read.
Next, Chapter 5 builds the modest amount of mathematical intuition — vectors, probability, and gradients — that makes the inner workings of models finally click into place.
Exercises
- 1Create variables for your name, your age, and a topic you enjoy, then use an f-string to print a single sentence introducing yourself.
- 2Make a list of five document titles. Print the third one, add a sixth title with `append`, and then print how many titles the list now holds.
- 3Build a dictionary describing a book, with keys for title, author, and pages. Print the author, then add a new key for the year it was published.
- 4Write a function that takes a list of numbers and returns their average, returning 0 for an empty list. Test it on three different lists, including an empty one.
- 5Write a short script that loops over a list of message dictionaries (each with a `role` and `content`) and prints each one in the format `role: content`.
- 6Rewrite your average function in JavaScript. You do not need to run it — the goal is simply to feel how the same idea looks in another language.
