Python Essentials for AI

Not all of Python — just the parts every later page leans on. By the end you will read a traceback calmly and have written a small program that scores restaurant reviews as positive or negative.

A food stall owner in Ipoh has three hundred online reviews and one question: are people happier this month than last? A spreadsheet can count rows, but it cannot easily read sentences. Forty lines of Python can. That is the scale of program this page builds towards — small, honest and useful — and every idea on the way is one you will meet again when you train models and call language-model APIs later in the track.

Two ways to run Python

Python is a programming language designed to be read by people as much as by computers. If you followed the set-up on The Builder’s Road, you already have Python, an editor and a virtual environment. There are two common ways to run code, and you will use both.

A script is a plain text file ending in .py. You run the whole file from top to bottom with a terminal command such as python hello.py (on Windows often py hello.py). Each run starts fresh: nothing is remembered from the last one. Scripts are what you share, schedule and put into real applications.

Here is the smallest possible script. Save it as hello.py and run it.

Every example on this page was run with Python 3.13 and NumPy 2.5 As of 2026; the output blocks are pasted from those runs.

print("Selamat pagi from Python!")
print(2 + 3 * 4)
Selamat pagi from Python!
14

print shows whatever you give it. The second line shows that Python follows the school rule for arithmetic: multiplication before addition, so the answer is 14, not 20. Text goes inside quotation marks; numbers do not.

Values, lists and dictionaries

A variable is a name attached to a value. You create one with =, which in Python means “make this name point at this value”, not “is equal to”. Every value has a type, and the type decides what you can do with it.

name = "Aisyah"          # text: a string (str)
age = 29                 # a whole number (int)
height_m = 1.62          # a decimal number (float)
is_student = False       # True or False (bool)

print(name, age, height_m, is_student)
print(type(name), type(age), type(height_m), type(is_student))
print(age + 1, height_m * 100, name.upper())
print("29" + "1", int("29") + 1)
Aisyah 29 1.62 False
<class 'str'> <class 'int'> <class 'float'> <class 'bool'>
30 162.0 AISYAH
291 30

The four basic types are str (text), int (whole numbers), float (numbers with a decimal point) and bool (True or False). The last line is the one to remember: "29" + "1" glues two pieces of text into "291", while int("29") + 1 converts the text to a number first and gives 30. Numbers that arrive from files and web forms usually arrive as text, and this exact confusion is behind many data bugs — you will meet it again on Working with Data. Anything after # is a comment for human readers; Python ignores it.

Single values only get you so far. Python’s two workhorse containers are the list, an ordered sequence, and the dictionary (dict), a lookup table from keys to values.

cities = ["Kuala Lumpur", "George Town", "Johor Bahru"]
cities.append("Kuching")
print(cities[0], "|", cities[-1], "|", len(cities))
print(cities[1:3])

prices = {"nasi lemak": 3.50, "roti canai": 1.80, "teh tarik": 2.20}
prices["kopi o"] = 1.90
print(prices["teh tarik"])
print(prices.get("milo ais", "not on the menu"))
print(list(prices.keys()))
Kuala Lumpur | Kuching | 4
['George Town', 'Johor Bahru']
2.2
not on the menu
['nasi lemak', 'roti canai', 'teh tarik', 'kopi o']

Almost all data in AI work is some mix of these two. A row of a spreadsheet is like a dictionary (column name → value); a whole sheet is like a list of those dictionaries; a sentence split into words is a list of strings; a word count is a dictionary of word → number.

Loops, comprehensions and functions

A for loop repeats a block of code once for each item in a collection. The block is marked by indentation — four spaces — rather than brackets, so in Python the spacing is part of the meaning.

prices = {"nasi lemak": 3.50, "roti canai": 1.80, "teh tarik": 2.20, "kopi o": 1.90}

total = 0
for item, price in prices.items():
    print(item, "costs", price)
    total = total + price
print("One of everything:", total)

cheap = [item for item, price in prices.items() if price < 2]
print(cheap)

raised = {item: round(price * 1.10, 2) for item, price in prices.items()}
print(raised)
nasi lemak costs 3.5
roti canai costs 1.8
teh tarik costs 2.2
kopi o costs 1.9
One of everything: 9.4
['roti canai', 'kopi o']
{'nasi lemak': 3.85, 'roti canai': 1.98, 'teh tarik': 2.42, 'kopi o': 2.09}

The loop visits each item, price pair from prices.items(), prints it and adds the price to a running total. The two lines after it are comprehensions: compact one-line loops that build a new collection. [item for item, price in prices.items() if price < 2] reads almost as English: “the item, for each item and price, if the price is under 2.” The dictionary version builds a new menu with every price raised by 10%. Learn to read them even if you write ordinary loops at first.

When you find yourself writing the same few lines twice, wrap them in a function. A function has a name, takes inputs (arguments), and gives back a result with return.

prices = {"nasi lemak": 3.50, "roti canai": 1.80, "teh tarik": 2.20, "kopi o": 1.90}

def order_total(order, service_charge=0.0):
    """Add up an order like {"nasi lemak": 2} and apply an optional charge."""
    subtotal = 0
    for item, quantity in order.items():
        subtotal += prices[item] * quantity
    return subtotal * (1 + service_charge)

breakfast = {"nasi lemak": 2, "teh tarik": 2}
print(f"Total: RM{order_total(breakfast):.2f}")
print(f"With 10% service charge: RM{order_total(breakfast, 0.10):.2f}")
items = len(breakfast)
print(f"{items} kinds of item, {sum(breakfast.values())} things in all")
Total: RM11.40
With 10% service charge: RM12.54
2 kinds of item, 4 things in all
Key point

Functions are how programs stay understandable. A good function does one job, has a name that says what that job is, and can be tested on its own. Later pages wrap “clean the data”, “train the model” and “ask the language model” in functions for exactly this reason.

Files and libraries

Real data lives in files, and the most common format is CSV — comma-separated values, the plain-text cousin of a spreadsheet. Python’s standard library (the toolbox that ships with Python) can read it. This example first writes a tiny reviews.csv so that it runs anywhere, then reads it back.

import csv
from pathlib import Path

# create a small CSV file so this example is self-contained
Path("reviews.csv").write_text(
    "id,review\n"
    "1,The nasi lemak was great and the service was fast\n"
    "2,\"Terrible wait, and the food was cold\"\n"
    "3,Good value but the place was noisy\n",
    encoding="utf-8",
)

with open("reviews.csv", newline="", encoding="utf-8") as f:
    rows = list(csv.DictReader(f))

print(len(rows), "rows")
print(rows[1])
for row in rows:
    print(row["id"], "->", row["review"][:25])
3 rows
{'id': '2', 'review': 'Terrible wait, and the food was cold'}
1 -> The nasi lemak was great 
2 -> Terrible wait, and the fo
3 -> Good value but the place 

with open(…) as f: opens the file and guarantees it is closed again when the indented block ends, even if something goes wrong. encoding="utf-8" avoids garbled characters on Windows, and newline="" is what the csv documentation asks for. csv.DictReader turns each row into a dictionary keyed by the header line, so you can write row["review"] instead of remembering column numbers. Notice two details: the review containing a comma was wrapped in double quotes in the file, which is how CSV keeps it as one field; and id came back as the text '2', not the number 2. CSV has no types — everything is text until you convert it.

The lines starting import bring in libraries: code other people have written, tested and documented. Some come with Python; others you install with pip.

import math
import random
import statistics
from collections import Counter

import numpy as np   # installed with pip, not part of Python itself

print(math.sqrt(144))
print(statistics.mean([3.5, 1.8, 2.2, 1.9]))
print(Counter("mississippi").most_common(2))

random.seed(42)              # same "random" numbers every run
print(random.randint(1, 6), random.randint(1, 6))
print(np.array([1, 2, 3]) * 10)
12.0
2.35
[('i', 4), ('s', 4)]
6 1
[10 20 30]

math, random, statistics and collections come with Python. numpy does not: it was installed with pip install numpy, and as np gives it the short nickname almost everyone uses. Counter counts things — here the letters of “mississippi”. random.seed(42) fixes the starting point of the random number generator, so you get the same “random” dice rolls as this page every time; machine-learning code does the same so that results can be reproduced. Any fixed number works.

The rule of thumb for AI work: before writing something yourself, assume a well-known library already does it. Most of this track is learning a handful of them — NumPy, pandas and scikit-learn next, then the model providers’ SDKs.

Reading error messages

Your programs will crash. Everyone’s do, constantly. The skill is not avoiding errors but reading them quickly. When Python crashes it prints a traceback. Here is a small program with a deliberate mistake: the order spells “teh-tarik” with a hyphen, but the menu has “teh tarik” with a space.

prices = {"nasi lemak": 3.50, "teh tarik": 2.20}

def order_total(order):
    total = 0
    for item, quantity in order.items():
        total += prices[item] * quantity
    return total

print(order_total({"nasi lemak": 1, "teh-tarik": 2}))
Traceback (most recent call last):
  File "C:\Users\you\ai-builder\order.py", line 9, in <module>
    print(order_total({"nasi lemak": 1, "teh-tarik": 2}))
          ~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\you\ai-builder\order.py", line 6, in order_total
    total += prices[item] * quantity
             ~~~~~~^^^^^^
KeyError: 'teh-tarik'

Your folder path will differ; the start of the path has been shortened here.

Tracebacks look alarming, but they have a fixed shape. Step through it in the order an experienced programmer reads it:

A handful of error types cover most beginner crashes. NameError: you used a name Python has not seen — usually a typo or a missing import. TypeError: you combined types that do not mix, such as "Total: " + 5. KeyError and IndexError: you asked a dictionary or list for something it does not have. IndentationError: the spacing is inconsistent. ModuleNotFoundError: a library is not installed in the environment you are running — often because the virtual environment is not switched on.

One more, from the writing of this very page. Saving an example as types.py broke a different script in the same folder: Python’s own standard library has a module called types, and a file of yours with the same name gets imported in its place. Recent Python versions spot this and end the traceback with a hint to rename the file. Avoid naming your files random.py, csv.py, types.py or after any library you import.

Learning with an AI assistant, not through it

An AI coding assistant — Claude, ChatGPT, Gemini, GitHub Copilot and others — can explain any line on this page, suggest fixes and write whole programs. That is a gift for learning and a hazard for understanding. This guide’s framing The test is simple: if the assistant disappeared tomorrow, could you explain what your code does and how you would check it? Ask in ways that keep the thinking with you.

Outsources the understanding
My code doesn’t work, fix it.
Keeps you learning
I am learning Python. My script crashes with KeyError: 'teh-tarik' on the line total += prices[item] * quantity. Explain what a KeyError means and give me two hints about where to look, but do not write the fix for me yet.

Other habits that work: paste only the traceback and the few relevant lines, never secrets or confidential data, and check your workplace rules before sharing work code. Ask the assistant to explain code line by line before you run it. Ask for a small test that would prove the code right or wrong. When it suggests a library function, check it exists in the official documentation — assistants sometimes invent plausible-sounding functions, and an AttributeError is usually the first sign. Then retype the fix yourself rather than pasting it; your fingers learn the syntax faster than your eyes.

Putting it together: a tiny sentiment scorer

Time to build the program from the opening. It reads reviews from a CSV file, splits each into words, and scores it by counting words from a positive list and a negative list. This is the oldest and simplest form of sentiment analysis, called a lexicon method — real systems use trained models, but the shape of the program (load, clean, score, report) stays the same.

import csv
import string
from collections import Counter
from pathlib import Path

Path("reviews.csv").write_text(
    "id,review\n"
    "1,The nasi lemak was great and the service was fast\n"
    "2,\"Terrible wait, and the food was cold\"\n"
    "3,Good value but the place was noisy\n"
    "4,Sambal sedap! Friendly staff and great teh tarik\n"
    "5,\"Slow, rude and dirty. Never again.\"\n",
    encoding="utf-8",
)

POSITIVE = {"great", "good", "fast", "friendly", "value", "sedap", "delicious"}
NEGATIVE = {"terrible", "cold", "slow", "rude", "dirty", "noisy", "never"}

def clean_words(text):
    """Lower-case, strip punctuation, split into words."""
    text = text.lower()
    for mark in string.punctuation:
        text = text.replace(mark, " ")
    return text.split()

def score(words):
    pos = sum(1 for w in words if w in POSITIVE)
    neg = sum(1 for w in words if w in NEGATIVE)
    return pos - neg

with open("reviews.csv", newline="", encoding="utf-8") as f:
    reviews = list(csv.DictReader(f))

all_words = Counter()
for r in reviews:
    words = clean_words(r["review"])
    all_words.update(words)
    s = score(words)
    label = "positive" if s > 0 else "negative" if s < 0 else "neutral"
    print(f"Review {r['id']}: score {s:+d} ({label})")

print("Most common words:", all_words.most_common(4))
Review 1: score +2 (positive)
Review 2: score -2 (negative)
Review 3: score +1 (positive)
Review 4: score +3 (positive)
Review 5: score -4 (negative)
Most common words: [('the', 4), ('was', 4), ('and', 4), ('great', 2)]

The scorer is easy to fool. “Not good” scores +1. “The sambal was not terrible” scores −1. Sarcasm defeats it completely. Those failures are the reason the field moved from word lists to models that learn from labelled examples — the subject of The Machine Learning Workflow — and, much later, to language models that read whole sentences.

Quick check

What does "5" + "5" give in Python?

Both values are text (strings), so + joins them. Convert first with int("5") to do arithmetic.

A traceback ends with NameError: name 'pirnt' is not defined. What is the most likely fix?

NameError means Python has never seen that name — almost always a typo or a missing import.

You need to look up a price by the name of a dish. Which container fits best?

Dictionaries map keys (dish names) to values (prices). A list would make you search by position.

Why does the sentiment script call clean_words before scoring?

Without lower-casing and removing punctuation, the same word in different forms would not match the word lists.

Try this

Extend the sentiment scorer so that a negative word straight after “not” or “tak” flips sign: “not bad” should count as positive. Hint: loop over positions with for i in range(len(words)) and look at words[i - 1]. Add three reviews of your own (made up, no real names) that test the new rule, and one that still fools it.

// Pause and reflect

  1. Which idea on this page felt least natural — zero-based counting, indentation, dictionaries, or reading tracebacks — and what small exercise would make it stick?
  2. Think of a text file or spreadsheet you deal with regularly. What would a forty-line script do with it?
  3. Write down one rule you will follow when asking an AI assistant for coding help.

Your notes are saved privately in this browser.

Key terms on this page

Sources & further reading