Python masterclass

Python masterclass

1 of 112

Python masterclass

  • How your code runs and a professional work environment
  • The fundamentals with the right mental model
  • A real script: the month's expenses, from a CSV to a summary

This is the whole masterclass, on one page. Above are the slides we go through together; below, the full reading with every example, its commented code and the real output it prints.

How the session works

The masterclass has one concrete goal: that you finish able to actually work with Python. To get there you will understand how your code runs, set up a professional work environment, go through the fundamentals with the right mental model and build a real script that reads the month's expenses from a CSV, adds them up by category and saves a summary.

The session mixes four things:

  • Theory with diagrams. Every important idea shows up drawn before you see it in code.
  • Examples with real output. Every example was really run, and you see exactly what it prints. When an output surprises you, that is where your mental model gets corrected.
  • Practice in Colab. A notebook with 14 exercises, in the order of the session, to work through at your own pace. It is at the end of this lesson, in the Exercises section.
  • This reading. All the code from the slides is here, with comments, the file it goes in, the command to run it and the real output it printed.

Every output on this page came from running the code with Python 3.14 and uv. None of it is made up.

The session map

There are nine parts in three stages:

StageParts
Understand1. What Python is and how your code runs · 2. Your work environment
The fundamentals3. Values, names and objects · 4. Decisions and repetition · 5. Collections · 6. Functions
Real work7. Errors and exceptions · 8. Modules, packages and files · 9. The mini project

One example ties everything together: the month's expenses. Each part builds one piece of the final script, report.py, inside the expenses-lab project.

The kitchen analogy

You will see this analogy throughout the session. There is only one, so new ideas have something to hold on to:

PythonKitchen
script, the programthe recipe: steps in order
interpreter (CPython)the cook who reads the recipe from top to bottom
variablethe label stuck on the jar; the jar is the object
list and dictionarythe shelf with jars in order and the spice rack where you look things up by name
functiona named sub-recipe: it takes ingredients and gives back a result
traceback (the error)the cook stops and tells you at which step and why
.venv, packages and uvyour own kitchen per project, ingredients from the store (PyPI) and whoever stocks it and writes everything down
file on diskthe pantry: what is still there when you turn off the computer

Part 1: What Python is and how your code runs

In this part you will understand what happens between writing a text file and seeing a result in the terminal. That path explains why your code stops where it stops and helps you read errors.

What Python is and where it is used

Python is an interpreted language: you do not need to turn your program into an executable before using it. You write the file and Python runs it directly, so the cycle of writing, testing and fixing is very fast. It is general-purpose, not tied to one kind of problem, and it is made to be easy to read: its syntax looks like English and it uses indentation to mark blocks.

WhereWhat for
Backend and APIsweb servers, services
Datacleaning, analysis, reports
Artificial intelligencemodels and agents
Automationscripts that save you repetitive work

From your file to the output

When you type python hello.py, this happens:

  1. Your code is text. A .py file is plain text. That is why any editor opens it, and that is why spaces and indentation matter: Python reads them exactly as they are.
  2. The compiler checks and translates. The interpreter you use is called CPython. Before running, it checks that the whole file is well written and translates it. If there is a syntax error, for example an unclosed parenthesis, it stops here and not even the first line runs.
  3. The bytecode. The result of that translation is bytecode, CPython's internal representation of your program: very simple instructions. It is not machine code for your processor and it is not meant to be shared between Python versions.
  4. The virtual machine. Python's virtual machine runs those instructions one after another, from top to bottom, like the cook following the recipe.
  5. The output. Whatever you print with print shows up in the terminal. If something fails while running, Python stops and leaves you a traceback: the report of which line failed and why. You learn to read it in Part 7.

One detail you will see in your projects: when you import a module, Python saves its bytecode in a __pycache__ folder, in .pyc files, so it does not have to translate it again next time. It is only a cache: do not edit it or push it to git.

Bytecode, up close

So that bytecode does not stay an abstract word, here is the bytecode of a small function.

code/a/cache-demo/money.py:

def add_tip(amount, tip):
    return amount + tip
# A two-line function: it adds a tip to an amount.
# The comments go at the end so def stays on line 1 and return on line 2,
# which are the line numbers the disassembler shows.

code/a/cache-demo/app.py:

# Import the function from money.py (that is why Python saves its bytecode in __pycache__).
from money import add_tip

# 42.00 for dinner plus a 6.30 tip.
print(add_tip(42.00, 6.30))

Run app.py and look at the folder before and after:

# From the cache-demo folder
ls
python3.14 app.py
ls
ls __pycache__
app.py
money.py
48.3
__pycache__
app.py
money.py
money.cpython-314.pyc

The __pycache__ folder appeared after running, with money.cpython-314.pyc: the bytecode of money.py for CPython 3.14. app.py does not show up there because it is the file you ran directly, not one you imported.

To see the bytecode of add_tip, use the dis module, which comes with Python:

# From the cache-demo folder: import money and disassemble add_tip
python3.14 -c "import dis, money; dis.dis(money.add_tip)"
  1           RESUME                   0

  2           LOAD_FAST_BORROW_LOAD_FAST_BORROW 1 (amount, tip)
              BINARY_OP                0 (+)
              RETURN_VALUE

Line 2 of money.py became three instructions: load amount and tip, do the binary operation + and return the value. You do not need to memorize them, and they change between Python versions. What matters is the idea: your readable line turns into small steps that the virtual machine follows one by one, and when something fails, Python tells you which line of your file it was on.

Two ways to talk to Python

  • The interactive console (REPL). It stands for read, eval, print, loop: it reads what you type, evaluates it, prints the result and waits again. It is for trying an idea right away.
  • The script. A .py file that Python runs in full, from top to bottom. It is for what you want to keep, repeat and share.

The practical rule: you test in the console, you keep it in the file.

The interactive console, live

Open the terminal and type your system's Python command:

SystemCommand
Mac and Linuxpython3 (or python3.14)
Windowspy
Any, if you only installed uvuv run python

You will see >>>: Python is waiting. Type each line and press Enter:

>>> 2 + 3
5
>>> name = "Ana"
>>> name
'Ana'
>>> len(name)
3
  • 2 + 3 shows 5 without asking for print: in the console, the result of each expression shows up on its own.
  • name = "Ana" shows nothing: storing a value does not produce a result.
  • name shows 'Ana' with quotes, so you know it is text.
  • len(name) counts the letters: 3.

To leave, type exit and press Enter.

Your first script

code/a/en/hello.py:

# Store a piece of text under the name "name".
name = "Ana"
# Add the first two expenses of the month: groceries and the metro card.
total = 85.40 + 20.00
# An f-string: whatever goes inside the braces is replaced by its value.
print(f"Hello, {name}")
# print separates its values with a space.
print("You spent", total)
# From the folder where you saved hello.py (on Windows: py hello.py)
python3.14 hello.py
Hello, Ana
You spent 105.4

You wrote 85.40 + 20.00 and Python printed 105.4, without the trailing zeros. To Python that number is a value, not formatted text. If you want to always show two decimals, you decide that when printing; you will see it in Part 3.

An error on line 3: Python runs from top to bottom

code/a/en/three_steps.py:

print("Step 1: I read the recipe")
print("Step 2: I take out the ingredients")
print("Step 3: I cook", ingredient)
print("Step 4: I serve the dish")
# A four-step recipe. Careful: "ingredient" was never stored anywhere.
# The comment goes at the end so step 3 stays on line 3, as in the traceback.

Python does not check every name before it starts: it only checks that the file is well written. Names are looked up when each line runs, so you will see how far the script gets.

python3.14 three_steps.py
Step 1: I read the recipe
Step 2: I take out the ingredients
Traceback (most recent call last):
  File "/private/tmp/masterclass/three_steps.py", line 3, in <module>
    print("Step 3: I cook", ingredient)
                            ^^^^^^^^^^
NameError: name 'ingredient' is not defined

The path in the traceback is the folder where the test was run; on your machine you will see yours. Read two things: the line number and the last line. The error is on line 3, the ^^^^^^^^^^ marks point at the exact name, and it is a NameError: a name that is not defined.

Steps 1 and 2 did run and step 4 never came. The file was well written, so the compiler had nothing to complain about. A name that does not exist is only discovered when the virtual machine reaches that line and looks for it. With a syntax error instead (for example, an unclosed parenthesis), nothing is printed: the compiler catches it before starting.

Part 2: Your work environment

In this part you set up the work environment with three pieces: Python, uv to manage projects and packages, and VS Code to write code. The central idea: each project has its own kitchen, with its own ingredients, and no project breaks anything in another.

One Python for everything, or one kitchen per project

If you install every package into your computer's global Python, all your projects share one single place. Imagine expenses-lab needs the rich library at version 15 and an old project needs version 13. Only one version can be installed, so the last one you installed wins and the other project breaks without you touching it. (The old project's versions are an example to show the clash.)

The solution is one virtual environment per project: a .venv folder with its own Python and its own packages. The Python documentation defines it as an isolated environment that lets you install and upgrade packages without interfering with other applications on the same system.

  1. One single place breaks. If every project installs into the same Python, sooner or later two of them will ask for different versions of the same package.
  2. Each project, its own .venv. Its Python and its packages, isolated from the rest of the system.
  3. Disposable. If the environment breaks, you delete it and it is recreated the same, because the project has written down which version of everything goes there.

What you share is the list of ingredients, not the kitchen.

uv: three commands for the whole project

uv installs Python versions, creates projects, manages packages and runs your code. To start, you need three commands:

  1. uv init expenses-lab creates the project: pyproject.toml, a sample main.py, .python-version, README.md and, if you are not inside another git repository, a new repository with its .gitignore.
  2. uv add rich brings a package: it writes it down in pyproject.toml, records the exact versions in uv.lock and installs it in .venv.
  3. uv run main.py runs your code. Before running, uv checks that uv.lock is up to date with pyproject.toml and that the environment is up to date with uv.lock; if .venv does not exist, it creates it. That way you always run with the project's Python and packages.

Create your project with uv init

Open the terminal in the folder where you keep your projects:

# Create the project
uv init expenses-lab
# Go into the folder
cd expenses-lab
# Run the sample main.py (the first time, uv creates the virtual environment)
uv run main.py
Initialized project `expenses-lab` at `/private/tmp/masterclass/expenses-lab`
Using CPython 3.14.10
Creating virtual environment at: .venv
Hello from expenses-lab!

The path on the first line is from the test run; yours will be your own folder. Notice what uv run did before running your code: it said which Python it uses (CPython 3.14.10) and created the virtual environment in .venv, because it was needed. You did not ask it to.

This is the main.py that uv init creates:

# The project's main function.
def main():
    print("Hello from expenses-lab!")


# Only run main() if you run this file directly (we explain it in Part 8).
if __name__ == "__main__":
    main()

If uv is not recognized as a command, uv did not get installed or your terminal cannot find it: install it with the commands on its official page (docs.astral.sh/uv), close the terminal and open a new one. If you cannot install programs on your computer, all the code in Parts 3 to 7 also runs in Google Colab; do the uv project when you have a machine where you can install things.

uv add: bring an ingredient from the store

Python's store is PyPI, the package index. Add rich, a library to print nicely in the terminal (colors, tables, formatting):

# From the expenses-lab folder
uv add rich
Resolved 5 packages in 81ms
Installed 4 packages in 36ms
 + markdown-it-py==4.3.0
 + mdurl==0.1.2
 + pygments==2.21.0
 + rich==15.0.0
  • Resolved 5 packages: uv worked out which versions fit together. It counts five because it includes your own project.
  • Installed 4 packages: you asked for one, but rich needs others to work (pygments, for example, colors code). Those are its dependencies, and uv brings them on its own.
  • Everything was installed inside .venv, not on your computer in general. The times and exact versions may differ on your machine.

After uv add, pyproject.toml looks like this:

[project]
name = "expenses-lab"
version = "0.1.0"
description = "Add your description here"
readme = "README.md"
requires-python = ">=3.14"
dependencies = [
    "rich>=15.0.0",
]

Anatomy of the project

FileWhat it isGoes to git?
pyproject.tomlthe project's card: name, Python and what it needsyes
uv.lockwhat got installed, exactly, with every dependencyyes
.python-versionwhich Python the project uses (3.14)yes
main.pyyour codeyes
README.mdthe project's explanation for peopleyes
.gitignorewhat git does not push; includes .venvyes
.venv/the virtual environment: its own Python and the packagesno, it regenerates
__pycache__/the bytecode cacheno, it regenerates
  1. pyproject.toml stores what you ask for, with ranges: rich>=15.0.0 means "15.0.0 or any newer version". It is the intent.
  2. uv.lock stores what was actually installed, version by version. The uv documentation calls it a universal file: it works for Mac, Windows and Linux at the same time. It goes to git so everyone installs exactly the same thing.
  3. .python-version tells uv which Python to create the environment with.
  4. .venv/ is the kitchen. It is heavy, it depends on your operating system and it is recreated with uv sync or with the next uv run. Inside is the project's Python (.venv/bin/python on Mac and Linux, .venv\Scripts\python.exe on Windows).
  5. .gitignore, which uv already created, keeps .venv out of the repository.

The short rule: pyproject.toml is what you want; uv.lock is what you have.

The same file with python3.14 and with uv run

Change main.py to use rich:

code/a/en/expenses-lab/main.py:

from rich import print
# Line 1 brings in rich's print function, which replaces the built-in one and knows how to format.


def main():
    # [bold]...[/bold] is a rich markup tag: in a real terminal it shows in bold.
    print("[bold]expenses-lab[/bold] ready")
    # Three expense categories with their totals (you will compute them in the mini project).
    print({"food": 139.9, "transport": 34.3, "home": 28.74})


if __name__ == "__main__":
    main()

Now run it twice from the same folder: with your computer's Python (python3.14 main.py) and with uv run main.py. Same Python version, same file, but a different kitchen: rich lives only in the project's .venv.

# From the expenses-lab folder
python3.14 main.py
uv run main.py
Traceback (most recent call last):
  File "/private/tmp/masterclass/expenses-lab/main.py", line 1, in <module>
    from rich import print
ModuleNotFoundError: No module named 'rich'
expenses-lab ready
{'food': 139.9, 'transport': 34.3, 'home': 28.74}

With the computer's Python, the script fails on the first line: rich does not exist in that kitchen, because we never installed it there. With uv run it works, because uv run runs inside .venv, where rich is installed. It was the same Python version, but a different kitchen.

ModuleNotFoundError is one of the most common errors when you start, and it almost always means the same thing: you are running with a Python that is not your project's. That is why, in this session, everything runs with uv run.

VS Code: editor, terminal and the right interpreter

Use VS Code with the official Python extension. In one window you have:

  1. The explorer, with the project's files (pyproject.toml, uv.lock, .venv/...).
  2. The editor: when VS Code knows which Python to use, it autocompletes rich's functions and underlines errors while you type.
  3. The integrated terminal, where you run uv run without switching windows.
  4. The selected interpreter, in the status bar. It has to be the Python in your project's .venv. If VS Code uses another one, the editor will flag that rich does not exist even though uv run works, for the same reason as the example of the same file with python3.14 and with uv run. You change it with one click on the Python version in the status bar or with the Python: Select Interpreter command in the command palette.

Always open the whole project folder (File > Open Folder), not a single file, so VS Code finds its .venv.

The commands you take with you

CommandWhat it does
uv init namecreates the project
uv add packagebrings a package from PyPI, installs it in .venv and writes it down
uv run file.pyruns with the project's Python and packages
uv syncrecreates .venv from uv.lock (for example, after cloning a project)
uv run pythonopens the interactive console inside the project

Resources

Part 3: Values, names and objects

In this part you will understand what happens in memory when you write amount = 85.40. It looks like an obvious line, but the mental model you build here decides whether you understand the strangest bugs you will see later: a list that "changes by itself", a number that gets glued like text, a sum that does not add up.

Every example uses this month's expenses (expenses.csv) and runs the same way: save the file in your working folder and run it with python (or uv run python inside your project). The outputs you see here are the real ones.

Every value is an object with a type

In Python every value is an object, and every object has three things: an identity (which object it is), a type (what kind of thing it is) and a value. Today you use five basic types:

TypeExampleWhat for
float85.40numbers with decimals: amounts
int8whole numbers: how many rows there are
str"food"text: categories, descriptions
boolTrueyes or no: has it been paid?
NoneNone"there is nothing here yet"

The type() function tells you the type of any value.

types_demo.py:

# types_demo.py: every value knows its type
amount = 85.40          # float: a number with decimals
category = "food"       # str: text
paid = True             # bool: true or false
note = None             # None: "nothing here yet"
print(type(amount), type(8), type(category))   # 8 is an int
print(type(paid), type(note))

Command: python types_demo.py

<class 'float'> <class 'int'> <class 'str'>
<class 'bool'> <class 'NoneType'>

A name is a label, not a box

When you write amount = 85.40, Python does two things: it creates a float object with the value 85.4 and sticks the label amount on it. The name does not "hold" the number: it points to the object. In the kitchen, the object is the jar and the name is the label stuck on top.

That is why the type lives in the object, not in the name. The same name can point to a number today and to some text tomorrow.

Reassigning moves the label

Reassigning (total = total + 85.40) does not modify the old jar: Python computes a new object and moves the label to it. The previous object is left with no names pointing to it, and Python frees that memory whenever it suits it.

rebind.py:

# rebind.py: reassigning moves the label to another object
total = 0
print(total, type(total))
total = total + 85.40
print(total, type(total))
total = "done"
print(total, type(total))

Command: python rebind.py

0 <class 'int'>
85.4 <class 'float'>
done <class 'str'>

This is called dynamic typing: the name total does not have a fixed type; it has the type of the object it points to at that moment. It is convenient, and it is also the reason to give your variables clear names.

Mutable and immutable

Some objects can change on the inside and others cannot. Their type decides it:

  • Immutable: int, float, str, bool, None and tuple. Any "change" creates a new object. "food".upper() gives you "FOOD", but "food" stays the same.
  • Mutable: list, dict and set. Their methods (append, add, assigning a key) change the same object.

This difference matters as soon as two names point to the same object, which is exactly what happens in the next example.

Two names, one list

alias.py:

# alias.py: two names stuck on the same object
amounts = [85.40, 20.00]
backup = amounts          # does NOT copy: sticks another label on the same jar
backup.append(12.50)      # append changes the list in place
print(amounts)
print(backup is amounts)  # is: are they the same object?

Command: python alias.py

[85.4, 20.0, 12.5]
True

backup = amounts does not create a new list: it sticks a second label on the same object. When append changes the list, the change shows through both names, because there is only one list. The is operator confirms it: it compares identity, that is, whether both names point to the same object.

If what you want is a real backup, ask for a copy: amounts.copy() creates a new object with the same items.

copy_list.py:

# copy_list.py: a copy is a new object
amounts = [85.40, 20.00]
backup = amounts.copy()                      # new object, same items
print(backup == amounts, backup is amounts)  # same content, different object
backup.append(12.50)                         # only the copy grows
print(amounts, backup)

Command: python copy_list.py

True False
[85.4, 20.0] [85.4, 20.0, 12.5]

The difference between the two operators: == asks whether they have the same value; is asks whether they are the same object. copy() makes a shallow copy: the list is new, but if there were other lists inside it, those would be shared.

Text with values inside: f-strings

To show results you will build text with values in it. The modern way is the f-string: an f before the quotes and each value inside curly braces. After the colon comes the format: .2f means "with two decimals".

fstrings.py:

# fstrings.py: building text with values inside
category = "food"
total = 139.9
print(f"{category}: {total:.2f}")         # .2f = two decimals
print(category.upper(), len(category))   # str methods and functions

Command: python fstrings.py

food: 139.90
FOOD 4

From text to number

When you read a CSV file, everything arrives as text: the amount 85.40 is the str "85.40". And + between two pieces of text does not add: it glues them together.

text_plus_text.py:

# text_plus_text.py: in a CSV everything arrives as text
first = "85.40"
second = "20.00"
print(first + second)                 # str + str: glues the texts together
print(float(first) + float(second))   # converted to float: adds

Command: python text_plus_text.py

85.4020.00
105.4

To add, you first convert with float() (or int() for whole numbers). In the mini project this conversion lives in the parse_amount(text) function. And if the text is not a number, like "abc", float() raises a ValueError: we deal with that in the part about errors.

Part 4: Decisions and repetition

So far your program runs from top to bottom, line by line, like the cook following the recipe. In this part you teach it to decide (do one thing or another) and to repeat (do the same thing for each expense).

Comparing produces a bool

Every comparison (>, <, >=, <=, ==, !=) produces a bool: True or False. With and, or and not you combine them.

compare.py:

# compare.py: comparing produces a bool
amount = 85.40
category = "food"
print(amount > 50, amount == 85.4)                          # two comparisons
print(category != "fun", amount > 50 and category == "fun")  # and: both must be True

Command: python compare.py

True True
True False

Watch out for = and ==: one equals sign assigns (it sticks on a label), two equals signs compare.

What Python counts as false

An if accepts any value, not just True and False. Python counts as false None, False, zero of any numeric type and empty collections ("", [], {}, (), set()). Everything else counts as true.

truthy.py:

# truthy.py: values that count as false
for value in [0, 0.0, "", [], None, 12.5, "food", [1]]:
    print(repr(value), bool(value))   # repr shows the value with its quotes

Command: python truthy.py

0 False
0.0 False
'' False
[] False
None False
12.5 True
'food' True
[1] True

That is why you will see code like if rows:, which reads "if there are rows".

if, elif, else: the first True wins

An if evaluates its conditions from top to bottom and runs only the first block whose condition is True. elif means "otherwise, try this"; else means "if none of them held". Afterwards, the program continues on the line after the if.

size.py:

# size.py: one path out of three
amount = 42.00
if amount >= 50:              # False: this block is skipped
    print(amount, "big")
elif amount >= 15:            # True: it goes in here
    print(amount, "medium")
else:                         # never evaluated
    print(amount, "small")

Command: python size.py

42.0 medium

The order of the conditions matters: if you put amount >= 15 first, an 85 expense would also say "medium".

Indentation is the syntax

In Python, blocks are not marked with braces or with end: they are marked with the margin. The colon at the end of if, for or while opens a block, every line with four more spaces belongs to it, and moving back to the left closes it.

blocks.py:

# blocks.py: indentation decides what goes inside what
amounts = [85.40, 20.00, 12.50]
total = 0
for amount in amounts:               # opens the for block
    if amount > 50:                  # inside the for: runs on every pass
        print("big", amount)         # inside the if: only if it is over 50
    total = total + amount           # back at the for level
print("total:", total)               # outside the for: runs once

Command: python blocks.py

big 85.4
total: 117.9

If you forget the indentation, Python does not even start running the program: it warns you first. This file has no comments on purpose, so the line numbers match the message.

indent_error.py:

amount = 42.00
if amount >= 50:
print("big")

Command: python indent_error.py

  File "/private/tmp/expenses-lab/indent_error.py", line 3
    print("big")
    ^^^^^
IndentationError: expected an indented block after 'if' statement on line 2

The file path on your machine will be the one for your folder. What matters is the last line: what happened (expected an indented block) and where (line 3, after the if on line 2).

for: one item at a time

for walks through a collection and, on each pass, sticks the loop name (amount) on the next item. When the items run out, the for ends on its own. You do not need to count or know how many there are.

for_total.py:

# for_total.py: one item at a time
amounts = [85.40, 20.00, 12.50]
total = 0
for amount in amounts:            # on each pass, amount points to the next item
    total = total + amount        # accumulate
    print(amount, total)          # show the pass
print("total:", round(total, 2))  # outside the for: only once

Command: python for_total.py

85.4 85.4
20.0 105.4
12.5 117.9
total: 117.9

This pattern, an accumulator that starts at zero and grows on every pass, is exactly what total_by_category(rows) does in the mini project, but split by category.

range: counting without a list

range(start, stop) produces whole numbers from start up to just before stop. The end is never included.

range_end.py:

# range_end.py: which numbers does range(1, 5) give?
total = 0
for n in range(1, 5):      # 1, 2, 3, 4: the 5 is left out
    total = total + n
print(total)
print(list(range(1, 5)))   # list() shows the numbers in a range

Command: python range_end.py

10
[1, 2, 3, 4]

while: repeat as long as it holds

while repeats its block as long as the condition is true. You use it when you do not know in advance how many passes you will make. The question in the example: if you save 120 a month, how many months does it take to reach 500?

while_savings.py:

# while_savings.py: repeat while the condition is true
saved = 0
months = 0
while saved < 500:          # asked before every pass
    saved = saved + 120     # the body must move you toward False
    months = months + 1
print(months, saved)

Command: python while_savings.py

5 600

If the body never makes the condition become False, the loop never ends. If that happens to you in the terminal, you stop it with Ctrl + C.

break and continue

Inside a loop, continue jumps to the next item and break leaves the loop completely.

break_continue.py:

# break_continue.py: skip one pass or leave the loop
for amount in [85.40, 20.00, -5.00, 12.50, 999.00]:
    if amount < 0:
        continue          # negative amount: skip it and move to the next one
    if amount > 500:
        break             # suspicious amount: stop processing
    print(amount)

Command: python break_continue.py

85.4
20.0
12.5

The -5.00 was skipped, and the 999.00 stopped the loop before it was printed. With this you have the pieces to walk through the expenses one by one. What is missing is a place to keep them well organized: collections.

Resources

Part 5: Collections

Up to now, every name pointed to a single value. But your expenses file has eight rows, and a real month has hundreds. Collections keep many values under one name. Python comes with four that you will use every day.

CollectionHow you write itWhat it is for
list[85.4, 20.0]ordered data that will change
tuple("food", 85.4)ordered data that does not change
dict{"food": 97.9}looking up a value by its key
set{"food", "home"}unique values, no repeats

Watch the braces: {"food": 97.9} (with key and value pairs) is a dictionary; {"food", "home"} (without pairs) is a set.

The list: a shelf with jars in order

Think of a list as a shelf: each jar is a value, and the shelf keeps them in the order you put them there. To ask for a jar, you use its position, which is called an index.

  • The first item is index 0, not 1: the index says how many steps you move from the start.
  • Negative indexes count from the end: -1 is always the last one, no matter how many there are.
  • append() adds an item at the end. The new one becomes index 4 and also -1.

Slices: a piece of the list

A slice gives you a piece of the list. The trick to never getting it wrong: the numbers in a slice do not point at jars, they point at cuts between jars.

  • amounts[1:4] cuts at line 1 and at line 4: it gives you indexes 1, 2 and 3.
  • With no start ([:2]) it begins at the very beginning; with no end ([-2:]) it goes all the way to the last one.
  • The start is in and the end is out. That is why amounts[:4] and amounts[4:] split the list without overlapping.

Here is all of that running. File lists.py:

# A list of amounts: it goes inside square brackets, separated by commas
amounts = [85.40, 20.00, 12.50, 9.99]
# append() adds an item at the end of the list
amounts.append(14.30)
# The first one (index 0), the last one (index -1) and how many there are (len)
print(amounts[0], amounts[-1], len(amounts))
# Slice: cuts at 1 and at 4, gives you indexes 1, 2 and 3
print(amounts[1:4])
# The first two and the last two
print(amounts[:2], amounts[-2:])
python lists.py
85.4 14.3 5
[20.0, 12.5, 9.99]
[85.4, 20.0] [9.99, 14.3]

Notice one detail: you wrote 85.40 and Python prints 85.4. It is the same number; Python does not keep the zeros on the right of a number. And a slice always gives you back a new list.

Tuple and set

A tuple is like a list that does not change. It is perfect for one row of the expenses file: four pieces of data that belong together and stay fixed. A set keeps unique values: if you put the same value in it three times, it keeps one. File tuple_set.py:

# One row of the file as a tuple: it goes inside parentheses and does not change
row = ("2026-11-02", "food", "Groceries", 85.40)
# Unpacking: hands out the four values to four names, in order
date, category, description, amount = row
print(category, amount)
# A set: braces without pairs; repeats are dropped
categories = {"food", "transport", "food", "home", "food"}
# It counts 3, not 5: "food" stays only once
print(len(categories))
# A set has no guaranteed order: sorted() gives you a sorted list
print(sorted(categories))
python tuple_set.py
food 85.4
3
['food', 'home', 'transport']

The dictionary: the spice rack

To add up by category, you need to find the total for "food" without walking through everything. That is what the dictionary is for: it stores pairs of a key and a value. Think of a spice rack: you do not look for the third jar, you look for the one that says "cinnamon".

  • From the key, Python computes a fixed number called a hash, and with it jumps straight to the spot for that key, without checking the others. That is why looking something up in a dictionary stays fast even with thousands of keys.
  • For the same reason, the key has to be hashable: something whose value does not change, like a piece of text, a number or a tuple of those. A list cannot be a key.
  • If you ask for a key that does not exist with square brackets (totals["fun"]), the program stops with KeyError. With get() and a default value (totals.get("fun", 0)) you get that value back and keep going.

Example: assigning the same key twice

In the session we saw this example: what happens if you assign a key that already exists? File dict_same_key.py:

# A dictionary with two categories
totals = {"food": 85.40, "transport": 20.00}
# The key "food" already exists: this REPLACES its value, it does not add
totals["food"] = 12.50
# The key "home" does not exist: this adds it at the end
totals["home"] = 9.99
print(totals)
# "fun" is not there: get() returns the default value instead of an error
print(totals.get("fun", 0))
# How many keys there are
print(len(totals))
python dict_same_key.py
{'food': 12.5, 'transport': 20.0, 'home': 9.99}
0
3
  • Assigning a key that already exists replaces the value: it does not add and it does not keep two. In a dictionary every key shows up only once. When you accumulate totals, this is what you need to watch: if you write = instead of adding, you lose what was there before, without any warning.
  • Dictionaries keep insertion order, and updating a key does not change its place. That is why food is still first. Python guarantees this since version 3.7.

Which one do I use?

Do not choose out of habit: choose by how you are going to use the data.

  • In order, by position: a list if it will change (the amounts that keep coming in), a tuple if it is a fixed group (one row of the CSV).
  • Look up by name: a dictionary. It is the structure you will see most in real Python: settings, responses from an API, counts.
  • Know if something is already there, or remove repeats: a set. Asking whether a value is in a set is fast for the same reason as with a dictionary: it uses the hash.

In the mini project you use all four: rows as tuples, amounts in a list, totals in a dictionary and categories in a set.

Comprehension: a new list from another one

Building a list from another one is so common that Python has a short way to do it: the comprehension (list comprehension). You can almost read it out loud: "a, for each a in amounts, if a is greater than 15".

  • The for takes the items one by one.
  • The if is optional: it filters. With no if, everything passes.
  • The expression at the start decides what you keep: the same value or a transformed one.
  • The original list is not touched: a new list is always created.

File comprehension.py:

amounts = [85.40, 20.00, 12.50, 9.99, 14.30]
# Filter: keeps only the amounts greater than 15
big = [a for a in amounts if a > 15]
# Transform: each amount becomes a piece of text with two decimals
labels = [f"{a:.2f}" for a in amounts]
print(big)
print(labels)
python comprehension.py
[85.4, 20.0]
['85.40', '20.00', '12.50', '9.99', '14.30']

In labels the zeros on the right do show up: these are no longer numbers but formatted text (that is why there are quotes). Use the numbers for math and the text only for showing things. If the comprehension does not fit on one line that reads well, use a regular for.

Break

So far you know how Python runs, you have your working environment, you understand that a name is a label stuck on an object, and you know how to make decisions, repeat steps and keep lots of data under one name. What comes next turns a script into an organized program: functions, errors, modules and files.

Part 6: Functions

A big recipe has named sub-recipes, like "the base sauce": you write them once, and in the recipe you just say "make the base sauce". A function is exactly that: it takes data, does its job and returns a result. In this part two pieces of the mini project are born: parse_amount and total_by_category.

Anatomy of a function

In your expenses, every amount arrives as text, sometimes with spaces, and it has to be turned into a number. If you write that step by hand everywhere, the day the rule changes you have to change it in ten places. That is why you put it in a function.

  • def defines the function. Then comes the name and, inside the parentheses, the parameter: the name the incoming data will have. At the end, a colon.
  • Below it, indented, comes the body: the steps.
  • return hands over the result and ends the function right there.
  • Defining does not run anything. The function runs when you call it: the data in the call is assigned to the parameter, and the whole call is worth what came back.

parse_amount: your first function

File parse_amount.py:

# def + name + parameter in parentheses + colon
def parse_amount(text):
    # strip() removes the spaces on both sides; float() turns the text into a number
    return float(text.strip())

# Outside the function now (no indentation): we call it with text that has spaces
print(parse_amount(" 85.40 "))
# A call is worth what it returns, so you can use it inside a calculation
print(parse_amount("12.50") + parse_amount("20"))
python parse_amount.py
85.4
32.5

Now the rule for reading an amount lives in one single place. If tomorrow the amounts come with a currency sign, you change this function and the whole program is fixed.

Calling and returning, step by step

When one function calls another, the caller waits until the other one returns. In the diagram each column is a function and time flows downward; the dotted arrows are the returns.

There are never two functions working at once: each call goes in, works and returns before the next one starts.

total_by_category: adding up by category

The second piece of the project brings together everything from today: tuples, for, a dictionary, get() and parse_amount. File report_v1.py:

def parse_amount(text):
    # Turns an amount written as text (with or without spaces) into a number
    return float(text.strip())

def total_by_category(rows):
    # Starts with an empty dictionary: the spice rack with no jars
    totals = {}
    # Each row is a tuple (category, amount as text): the for unpacks it
    for category, text in rows:
        # What the category already had (or 0 if it is new) + this row's amount
        totals[category] = totals.get(category, 0) + parse_amount(text)
    # Returns the data; it does not print anything
    return totals

def main():
    # Three test rows: two for food and one for transport
    rows = [("food", "85.40"), ("transport", "20.00"), ("food", "12.50")]
    print(total_by_category(rows))

# Without this call, the file would only define functions and do nothing
main()
python report_v1.py
{'food': 97.9, 'transport': 20.0}

The key line is the one with get(): it takes what the category already had, or zero if it is the first time, adds the amount and stores it. It is the pattern for accumulating in a dictionary. With a plain = you would replace the total, as you saw in the repeated key example.

The call stack

To know where to go back to after each call, Python keeps a call stack. It works like a stack of plates: the last one you put on is the first one you take off. This drawing is a snapshot of the moment when report_v1.py is converting the "12.50".

  1. The module is at the bottom: it is the code in your file that is not inside any function. In errors it shows up as <module>.
  2. main() called another function and was paused, without losing anything it had.
  3. total_by_category is paused too, with its dictionary half done. Each of these is an execution frame: it keeps its local variables and where to continue when the one above finishes.
  4. parse_amount is at the top: it is the only thing running.
  5. return removes the top frame and hands the value to the one below, which continues right where it left off.

Since every frame has its own variables, two functions can use the same name without stepping on each other. And when something fails, Python prints this whole stack, from the oldest call to the most recent one: that is a traceback. Knowing how to read the stack is knowing how to read an error.

Scope: where Python looks for a name

When you use a name, Python looks for it in layers, from the inside out. The layers are known as LEGB:

  • L, local: the parameters and the variables created inside the function.
  • E, enclosing: any functions that wrap this one, if there are any.
  • G, global: the names created in the file, outside of functions.
  • B, built-in: what Python brings with it, like print, round and len.

From the outside you cannot see inside: local variables exist only while the function is running. File scope.py:

tax = 0.16  # global: lives in the file, outside any function

def with_tax(amount):
    total = amount * (1 + tax)  # local: total is born here; tax comes from the global layer
    return round(total, 2)  # round comes from the built-in layer

print(with_tax(100))
print(total)  # error on purpose: total was local and no longer exists here
python scope.py
116.0
Traceback (most recent call last):
  File "/private/tmp/expenses-lab/scope.py", line 8, in <module>
    print(total)  # error on purpose: total was local and no longer exists here
          ^^^^^
NameError: name 'total' is not defined

The File ... line shows the path of the file on the machine where it ran; on yours you will see your own path. Look at in <module>: that is the stack, with a single frame because the error happened in the file and not inside a function. The practical lesson: what a function computes comes out through its return, not through its variables. If you need the result outside, store it: price = with_tax(100).

Arguments by position, by name and by default

A parameter with = in the definition has a default value: if you do not send it, that one is used. When you call the function, you can pass the data by position (in order) or by name. File arguments.py:

# currency and decimals have a default value; amount is required
def format_amount(amount, currency="USD", decimals=2):
    return f"{amount:.{decimals}f} {currency}"

# Only the amount: both default values are used
print(format_amount(85.4))
# By position: the second value goes to currency
print(format_amount(85.4, "MXN"))
# By name: you skip currency and send decimals
print(format_amount(85.4, decimals=0))
python arguments.py
85.40 USD
85.40 MXN
85 USD

When a call has more than two pieces of data, pass them by name: it reads by itself and nobody mixes up the order.

Example: print is not return

It is the number one confusion for anyone starting out. File print_vs_return.py:

def show_total(amounts):
    # Prints the sum, but has no return
    print(sum(amounts))

# We store what the call returns
result = show_total([85.40, 12.50])
print(result)
python print_vs_return.py
97.9
None
  • print shows something to a person; return hands the value to the program so it can be stored, added up or passed to another function.
  • A function that ends without a return gives back None, Python's value for "nothing". The typical symptom: something looks fine on the screen, but the variable is None and the next calculation fails.

That is why the functions in the mini project return data, and only one, at the end, is in charge of printing.

Docstring and type hints

Two things that make your code professional, even though they do not change what it does. File hints.py:

# text: str says text should be a piece of text; -> float, that it returns a decimal number
def parse_amount(text: str) -> float:
    """Turn text like ' 85.40 ' into the number 85.4."""
    return float(text.strip())

print(parse_amount(" 85.40 "))
# Python keeps the docstring with the function
print(parse_amount.__doc__)
python hints.py
85.4
Turn text like ' 85.40 ' into the number 85.4.
  • Type hints (text: str, -> float) are hints: Python does not check them when it runs. They are there for you, for your editor and for tools like a type checker, which catch mistakes before running.
  • The docstring, inside triple quotes, describes the function. Your editor shows it when you hover over the name.

Rule for the project: every function gets both.

Resources

Part 7: Errors and exceptions

When something fails, Python does not stay quiet: it tells you what happened, on which line and with which data. In this part you learn to read that message (the traceback), to recognize the most common errors and to give your program a plan B with try and except, so one bad row does not take the whole thing down.

Think of it with the kitchen analogy: the interpreter is the cook who reads the recipe step by step. When a step cannot be done, the cook stops and tells you which step they stopped at and why.

Every example in this part was run in a folder called expenses-lab. On your machine, the path that shows up in the traceback will be the path to your own folder.

A program that fails halfway

This script turns three amounts from text into numbers. The third one, "abc", is not a number.

The parse_amount function turns the text of an amount into a number with float; the list has two good amounts and one mistyped amount. This file has no comments on purpose: the traceback repeats each line exactly as it is written, so what you see here is identical to what it prints.

fails.py:

def parse_amount(text):
    return float(text)

amounts = ["85.40", "12.50", "abc"]
for text in amounts:
    print(parse_amount(text))

Run it:

$ python3.14 fails.py
85.4
12.5
Traceback (most recent call last):
  File "/private/tmp/expenses-lab/fails.py", line 6, in <module>
    print(parse_amount(text))
          ~~~~~~~~~~~~^^^^^^
  File "/private/tmp/expenses-lab/fails.py", line 2, in parse_amount
    return float(text)
ValueError: could not convert string to float: 'abc'

Look at the first two lines: 85.4 and 12.5 were printed. Python runs line by line, from top to bottom; it does not check the whole program before starting. It stops right when it reaches the piece of data it cannot convert.

How to read a traceback

A traceback is read from the bottom up:

  1. The type and the message. The last line, ValueError: could not convert string to float: 'abc', says what happened (ValueError: the type of the data was right, text, but its value was no good) and with which data ('abc'). Very often the fix comes straight from here.
  2. Where it blew up. The last File ... block is the exact line that failed: line 2, inside parse_amount, on the return float(text).
  3. Who called it. The blocks above are the path that led there: line 6 of the main file (<module>), the print inside the for. Sometimes the line that blows up is fine and the problem comes from whoever passed it the data.
  4. The order. The header Traceback (most recent call last) reminds you that the most recent call is at the end.

Practical rule: read the last line first; then go up until you find one of your own files. When you use third-party packages, the traceback will go through files you did not write: what you need to change is almost always in the first file that is yours.

The ~~~~^^^^ marks under a line point at the exact part of the expression that failed. They are a visual aid from recent versions of Python.

The errors you will see most

Each of these files produces one of the most common errors. Here is the real last line of each traceback:

syntax_error.py:

amount = 60
if amount > 50       # the colon at the end of the if is missing
    print("big")
$ python3.14 syntax_error.py
SyntaxError: expected ':'

name_error.py:

total = 218.94
print(totl)          # typo: the name totl does not exist
$ python3.14 name_error.py
NameError: name 'totl' is not defined. Did you mean: 'total'?

type_error.py:

print("Total: " + 218.94)   # text + number cannot be added
$ python3.14 type_error.py
TypeError: can only concatenate str (not "float") to str

value_error.py:

float("abc")         # the type is right (text), the value is not
$ python3.14 value_error.py
ValueError: could not convert string to float: 'abc'

key_error.py:

totals = {"food": 139.9}
print(totals["rent"])       # that key does not exist in the dictionary
$ python3.14 key_error.py
KeyError: 'rent'

file_not_found.py:

open("data/expense.csv")    # the file is called expenses.csv, with an s
$ python3.14 file_not_found.py
FileNotFoundError: [Errno 2] No such file or directory: 'data/expense.csv'
ErrorWhat it meansFirst question to ask yourself
SyntaxErrorThe text is not valid PythonWhat is missing: a colon, a parenthesis, quotes?
NameErrorYou use a name that does not existDid I spell it right? Did I define it before using it?
TypeErrorYou mix types that do not combineWhat type does each value have? Use type()
ValueErrorThe type is right, the value is notWhat exact data arrived?
KeyErrorThe key is not in the dictionaryWhich keys does it have? Would get be better?
FileNotFoundErrorThere is no file at that pathWhich folder am I running from? Is the name right?

try and except: the plan B

In a real program you do not want one bad piece of data to stop everything. That is what try is for: you put plan A inside try and plan B inside except.

plan_b.py:

text = "abc"
try:
    # Plan A: what we expect to work
    amount = float(text)
except ValueError:
    # Plan B: only if float raised a ValueError
    print("not a number:", text)
# This line runs in both cases: the program keeps going
print("the program keeps going")
$ python3.14 plan_b.py
not a number: abc
the program keeps going

Notice two decisions:

  • You name the exact error (except ValueError). You do not catch everything: you catch only the problem you know how to handle. If a different error shows up, you want to see it, not hide it.
  • The program keeps going. After plan B, Python continues with the next line.

The path through try, except, else and finally

try has two more optional pieces:

  • else runs only if the try raised no error.
  • finally runs always, error or not.

try_except.py:

for text in ["42.00", "abc"]:
    try:
        # Plan A: only the line that can fail
        amount = float(text)
    except ValueError:
        # Plan B: the text was not a number
        print("not a number:", text)
    else:
        # Only if plan A worked
        print("ok:", amount)
    finally:
        # Always, no matter what
        print("checked:", text)
$ python3.14 try_except.py
ok: 42.0
checked: 42.00
not a number: abc
checked: abc

With "42.00" the path goes along the top (try, else, finally). With "abc" it goes along the bottom (try, except, finally).

Why does else exist if you could put the print("ok:", amount) inside the try? Because this way the try protects only the line that can fail. If you put more code in the try, you could accidentally catch a ValueError that came from another line. The official documentation recommends it for that same reason.

Watch out for one case: if an error of a different type (for example a TypeError) shows up inside the try and no except catches it, finally runs anyway and then the error keeps going up, as if there were no try.

try, except and finally: the order they run in

try_finally_order.py:

try:
    # float fails before print receives anything
    print(float("abc"))
except ValueError:
    print("B")
finally:
    # finally runs even though except already handled the error
    print("C")
$ python3.14 try_finally_order.py
B
C

No number comes out: Python evaluates from the inside out, so float("abc") fails before print receives a value, and the rest of the try is abandoned. Then except runs (it prints B) and, at the end, finally (it prints C), even though the error was already handled.

raise: your own rules

Sometimes the data is a valid number, but it makes no sense for your problem: a negative expense, for example. With raise you throw an error yourself, with a message that explains what happened.

Line by line: float(text) converts the text (if it is not a number, float already raises its own ValueError); the if checks your rule, an expense cannot be negative; if the rule breaks, raise throws a ValueError with a message that says what happened and with which data; if everything is fine, return gives back the number. Below, one call with a valid amount and another that breaks the rule. Like fails.py, it has no comments so the traceback matches line by line.

raise_demo.py:

def parse_amount(text):
    amount = float(text)
    if amount < 0:
        raise ValueError(f"negative amount: {amount}")
    return amount

print(parse_amount("20.00"))
print(parse_amount("-5"))
$ python3.14 raise_demo.py
20.0
Traceback (most recent call last):
  File "/private/tmp/expenses-lab/raise_demo.py", line 8, in <module>
    print(parse_amount("-5"))
          ~~~~~~~~~~~~^^^^^^
  File "/private/tmp/expenses-lab/raise_demo.py", line 4, in parse_amount
    raise ValueError(f"negative amount: {amount}")
ValueError: negative amount: -5.0

Why raise an error instead of just printing a warning? Because that way whoever calls the function decides what to do: stop the program, skip the row or ask for the data again. Your mini project uses this same parse_amount and catches its ValueError to skip the bad row: one way to fail, one plan B.

Part 8: Modules, packages and files

Until now everything lived in a single file and in the program's memory. In this part you split your code into several files, you tell apart what Python already ships with from what you install, and you learn to read and save data on disk: the pantry, what is still there when you turn off the computer.

Where Python looks for what you import

A module is simply a .py file. When you write import something, Python has to find that module, and it always looks in the same order:

  1. Built-in modules: the ones that come inside the interpreter itself, like sys.
  2. The folder of the script you ran: that is why a money.py sitting next to your app.py is found without you doing anything.
  3. The standard library: json, csv, pathlib and hundreds more modules that ship with Python. You do not install them.
  4. The virtual environment's site-packages folder: that is where uv add puts the packages you install from PyPI.

Python uses the first one it finds. If it does not find it anywhere, it raises ModuleNotFoundError. For example, inside expenses-lab, which does not have the rich package installed:

$ uv run python -c "import rich"
ModuleNotFoundError: No module named 'rich'

(That is the last line of the traceback.) That error almost always means one of two things: you did not install the package in this project, or you are running a different Python from the project's. That is why, inside a project, you always run with uv run: it uses the Python and the packages from the project's .venv.

One clarification: a package is a folder with modules inside, and what you install from PyPI is also called a package. To get started, it is enough to know that you import it the same way as a module.

Importing a module runs its code

Two files in the same folder.

money.py:

# Formats an amount: thousands separator and two decimals
def format_amount(amount):
    return f"{amount:,.2f}"

# A loose print, outside any function
print("money.py loaded as", __name__)

app.py:

# Imports the function from money.py (it is in the same folder)
from money import format_amount

print(format_amount(1234.5))

The question: when you run app.py, how many lines come out? What is the value of __name__ inside money.py at that moment?

$ python3.14 app.py
money.py loaded as money
1,234.50
$ python3.14 money.py
money.py loaded as __main__

Two lessons:

  • Importing runs the file. The first time you import a module, Python runs all of its top-level code, from top to bottom. That is why the loose print in money.py ran even though app.py only asked for a function.
  • __name__ depends on how the file was loaded. In the file you ran, __name__ is "__main__". In an imported module, it is the module's name ("money").

The if name guard

With that you can separate two uses of the same file: running it to test it, or importing it to reuse its functions.

money.py (version with the guard):

def format_amount(amount):
    return f"{amount:,.2f}"

# Only runs if this is the file you executed, not if someone imports it
if __name__ == "__main__":
    print(format_amount(1234.5))

app.py does not change. The two runs:

$ python3.14 money.py
1,234.50
$ python3.14 app.py
1,234.50

When you run money.py, the guard is true and the example gets printed. When you run app.py, money.py is imported, its __name__ is "money", the guard is false and it prints nothing on its own: the amount comes out only once, from app.py. That is why almost every Python script ends with this guard calling a main() function. Your report.py does too.

From the pantry to Python and back

Now files. What is in your program's memory is wiped when it ends; what you save to disk stays there. The round trip of the expenses looks like this:

The five details that prevent the most errors:

  1. The path. Path("data") / "expenses.csv" builds the path with the right separator for your system (\ on Windows, / on Mac and Linux). Building the path does not open anything yet.
  2. with and encoding. with open(...) closes the file when the block ends, even if something fails inside. And always write encoding="utf-8": if you leave it out, Python 3.14 uses the system's encoding, which on some Windows computers is not UTF-8 and breaks accented characters. (Python 3.15 makes UTF-8 the default, but writing it explicitly works on any version.)
  3. Everything arrives as text. The CSV reader gives you '85.40', with quotes: it is text until you convert it with float. That is why parse_amount exists.
  4. The way back. json.dumps turns a dictionary into text in JSON format, ready to be written to disk; json.loads takes the opposite road.
  5. Memory and disk. Whatever you do not save is lost when the program ends.

Reading the CSV with with

This script and the next one are run from the project folder, where data/expenses.csv lives.

read_csv.py:

import csv  # standard library: nothing to install

# The csv module asks for newline="" to read line breaks correctly
with open("data/expenses.csv", encoding="utf-8", newline="") as file:
    # DictReader uses the first line as the column names
    rows = list(csv.DictReader(file))
# The file is already closed here, but rows is still in memory
print(len(rows), "rows; first:", rows[0]["description"])
# type() tells you the type of the first row's amount
print(rows[0]["amount"], type(rows[0]["amount"]))
$ python3.14 read_csv.py
8 rows; first: Groceries
85.40 <class 'str'>

Eight rows: the header does not count as a row, it is used to name the keys. Each row is a dictionary like {'date': '2026-11-02', 'category': 'food', 'description': 'Groceries', 'amount': '85.40'}. And the amount is a str: text, until you convert it with float. We wrap it in list(...) so we have every row in memory before with closes the file.

Saving the result as JSON

write_json.py:

import json
from pathlib import Path

totals = {"food": 139.9, "transport": 34.3}
# dumps: dictionary to JSON text; indent=2 makes it easy to read
# write_text opens, writes and closes the file in a single call
Path("totals.json").write_text(json.dumps(totals, indent=2), encoding="utf-8")
# Check: we read the text back and loads turns it into a dictionary again
print(json.loads(Path("totals.json").read_text(encoding="utf-8")))
$ python3.14 write_json.py
{'food': 139.9, 'transport': 34.3}

And this is the file left on disk, totals.json:

{
  "food": 139.9,
  "transport": 34.3
}

JSON is a text format that almost any language and tool can read. That is why it beats a format you make up yourself.

Part 9: The mini project

Now you put everything together in expenses-lab: a program that reads the month's expenses, adds up how much went into each category and saves the summary to disk. You have already seen every piece in some part of the masterclass.

The structure of expenses-lab

If you do not have it yet, create the project and go into its folder:

uv init expenses-lab
cd expenses-lab

uv init creates an example main.py. Rename it to report.py (or create report.py and delete main.py). Then create the data/ folder and copy expenses.csv and expenses-with-bad-row.csv into it.

  • pyproject.toml describes the project and the Python version it asks for (requires-python = ">=3.14").
  • uv.lock records the exact versions of the dependencies. This project only uses the standard library, so the lock has almost nothing in it:
version = 1
revision = 3
requires-python = ">=3.14"

[[package]]
name = "expenses-lab"
version = "0.1.0"
source = { virtual = "." }
  • report.py is the only code file you write.
  • data/ holds the inputs; summary.json is the output the program writes.
  • .venv/ is created by uv run the first time. It is the project's own kitchen: you do not edit it by hand.

The two input files, data/expenses.csv:

date,category,description,amount
2026-11-02,food,Groceries,85.40
2026-11-03,transport,Metro card,20.00
2026-11-05,food,Coffee beans,12.50
2026-11-08,home,Light bulbs,9.99
2026-11-12,transport,Taxi,14.30
2026-11-15,food,Restaurant,42.00
2026-11-20,home,Cleaning supplies,18.75
2026-11-24,fun,Movie tickets,16.00

and data/expenses-with-bad-row.csv, which is the same with one more row at the end:

2026-11-26,food,Snacks,abc

How the data flows

main() is the main recipe: it does not compute anything, it only calls the sub-recipes in order. Each function does one single thing:

  1. read_rows: from disk to a list of dictionaries, with with and utf-8.
  2. parse_amount: turns the text into a number and applies your rules with raise. It is the only one that knows what a valid amount is.
  3. total_by_category: the heart. A for to go through the rows, a dictionary to accumulate by category and a try per row for plan B.
  4. print_summary: the table on the screen, with fixed-width f-strings so it lines up.
  5. save_summary: the totals to JSON, rounded to two decimals.

One function, one responsibility. If tomorrow the file changes format, you only change read_rows. If you want a different output, you only change print_summary.

The full code of report.py

report.py:

"""Summarize the month's expenses by category and save the result to summary.json."""

import csv
import json
import sys
from pathlib import Path


def read_rows(path):
    """Read the CSV and return a list of dictionaries, one per row."""
    # with closes the file when the block ends, even if something fails inside
    with open(path, encoding="utf-8", newline="") as file:
        return list(csv.DictReader(file))


def parse_amount(text):
    """Turn the amount text into a number; reject negative amounts."""
    amount = float(text)  # raises ValueError if the text is not a number
    if amount < 0:
        raise ValueError(f"negative amount: {amount}")
    return amount


def total_by_category(rows):
    """Add up the amounts of each category and skip rows with an invalid amount."""
    totals = {}
    for row in rows:
        try:
            amount = parse_amount(row["amount"])
        except ValueError:
            # Plan B: say which row was skipped and move on to the next one
            print(f"Skipped {row['date']}: {row['amount']!r} is not a valid amount")
            continue
        category = row["category"]
        # get returns 0 the first time we see the category
        totals[category] = totals.get(category, 0) + amount
    return totals


def print_summary(totals):
    """Print a table: one line per category and the total at the end."""
    for category, amount in totals.items():
        print(f"{category:<10} {amount:>8.2f}")
    print(f"{'total':<10} {sum(totals.values()):>8.2f}")


def save_summary(totals, path):
    """Save the totals as JSON, rounded to two decimals."""
    rounded = {category: round(amount, 2) for category, amount in totals.items()}
    Path(path).write_text(json.dumps(rounded, indent=2), encoding="utf-8")


def main():
    # The input file comes as an argument; if not, we use the usual one
    path = sys.argv[1] if len(sys.argv) > 1 else "data/expenses.csv"
    try:
        rows = read_rows(path)
    except FileNotFoundError:
        print(f"File not found: {path}")
        return
    totals = total_by_category(rows)
    print_summary(totals)
    save_summary(totals, "summary.json")
    print(f"Saved summary.json with {len(totals)} categories")


# Only run main() when you execute this file, not when someone imports it
if __name__ == "__main__":
    main()

The details worth a second look:

  • totals.get(category, 0): the first time a category shows up, get returns 0 instead of raising a KeyError. That way you do not have to ask first whether the key exists.
  • continue: inside the except, it jumps straight to the next row without adding anything.
  • {row['amount']!r}: the !r shows the value as it is, with quotes ('abc'), so it is clear exactly what text arrived.
  • {category:<10} and {amount:>8.2f}: fixed width. <10 left-aligns the text in 10 characters; >8.2f right-aligns the number in 8 characters with two decimals. That way the table lines up in columns.
  • sys.argv: the list of what you typed in the terminal. sys.argv[1] is the first argument after the script name; if there is none, data/expenses.csv is used.
  • except FileNotFoundError in main: if you mistype the path, the program tells you in one line instead of a traceback.

The real run

From the expenses-lab folder:

$ uv run report.py
Using CPython 3.14.10
Creating virtual environment at: .venv
food         139.90
transport     34.30
home          28.74
fun           16.00
total        218.94
Saved summary.json with 4 categories

The first two lines come from uv, not from your program: since it is the first time, uv finds the Python the project asks for and creates the .venv. In later runs they no longer show up. The file left on disk, summary.json:

{
  "food": 139.9,
  "transport": 34.3,
  "home": 28.74,
  "fun": 16.0
}

And if you mistype the path of the input file:

$ uv run report.py data/expense.csv
File not found: data/expense.csv

The bad row: the program skips it and keeps going

Now you pass it the file that has one more row, 2026-11-26,food,Snacks,abc. total_by_category catches the ValueError, skips the row and keeps going: the program does not crash and the totals do not change.

$ uv run report.py data/expenses-with-bad-row.csv
Skipped 2026-11-26: 'abc' is not a valid amount
food         139.90
transport     34.30
home          28.74
fun           16.00
total        218.94
Saved summary.json with 4 categories

The program does not crash and does not make up a number: it says which row it skipped, with the data exactly as it came, and food is still at 139.90. The total is identical to the good run.

And look at who does what: parse_amount detects the problem (because float fails), but total_by_category decides what to do about it (skip the row). The function that converts does not know whether it is better to skip, to stop everything or to ask for help; the one with the context decides.

Wrap-up

Everything report.py uses

Every part of the masterclass is inside report.py:

PartWhat it brings to report.py
1 and 2The interpreter that reads from top to bottom, uv run and one .venv per project
3, 4 and 5Names like rows and totals, the for and the if, the list of rows and the dictionary of totals
6Six named functions and a main() that puts them in order
7The plan B for the bad row and your own rules with raise
8 and 9csv, json, pathlib, the if __name__ guard and a result saved to disk

Your next step

  • Practice with your own problems. One small script per real problem: organize a folder, add up a column, clean a file. Each one with its own uv init and its own uv run.
  • Read the traceback before searching the internet. The last line first; then go up until you reach one of your own files.
  • Keep going with the NIEVA Python Mini-Bootcamp: it is open and free, you take it at your own pace, and it takes you from your first line of code to a complete CRUD project with persistence, modules and error handling, in 9 modules.
  • Open guides to review: the Python Essentials Guide and the Modern Python Tooling Guide, which explains which interpreter runs your project, where dependencies live and which tools check your code.

Resources

Exercises

Do these exercises in the practice notebook: Open in Colab. First go to File > Save a copy in Drive and work in your copy. Below are the instructions and the solutions to compare when you finish.

Exercise 1: Your first program (Part 1)

Store your name in a variable and two expenses in two more: coffee = 85.40 and taxi = 12.50. With print(), show a greeting with your name and, on another line, how much you spent in total.

Solution.

# Store your name and two amounts in variables
name = "Ana"
coffee = 85.40
taxi = 12.50

# print puts a space between each thing you pass it
print("Hello,", name)
print("You spent", coffee + taxi)

Output:

Hello, Ana
You spent 97.9

Exercise 2: Read the error (Part 1)

Run the code cell below exactly as it is. It has an error on purpose. Then, in the text cell, answer: which steps got printed? On which line did it stop? What type of error does the last line say?

Solution. step 1 and step 2 get printed. The program stops on line 3, print(totl), with a NameError: the name totl does not exist. Python runs from top to bottom and stops at the first line that fails, so step 4 never gets printed. To fix it, create the variable before using it:

print("step 1")
print("step 2")
totl = 218.94  # the name already exists when you use it
print(totl)
print("step 4")

Exercise 3: Which Python does Colab use? (Part 2)

Colab already has Python installed on a machine in the cloud: it is another "kitchen", different from your laptop. Import the sys module and show sys.version.

Solution.

import sys  # sys knows which Python you are running

print(sys.version)

The output is a line that starts with 3.; the exact number depends on the version Colab has that day, and it may not be the one on your laptop. That is why a project declares its version in .python-version and uv respects it.

Exercise 4: Text that looks like a number (Part 3)

Create amount_a = "85.40" and amount_b = "12.50" (with quotes: they are text, as they arrive from a file). First print amount_a + amount_b. Then convert them with float(), add them and show the total with two decimals using an f-string.

Solution.

# The amounts arrive as text, as if they came from a file
amount_a = "85.40"
amount_b = "12.50"

# With text, + glues the texts together: it does not add
print(amount_a + amount_b)

# float turns the text into a number; now + does add
total = float(amount_a) + float(amount_b)
print(f"Total: {total:.2f}")

Output:

85.4012.50
Total: 97.90

Exercise 5: A copy, not another label (Part 3)

Create amounts = [85.40, 20.00] and a backup with backup = amounts.copy(). Add 12.50 to amounts with append. Print both lists and amounts is backup.

Solution.

amounts = [85.40, 20.00]

# copy() creates a new list; backup no longer points to the same object
backup = amounts.copy()
amounts.append(12.50)

print(amounts)
print(backup)
print(amounts is backup)

Output:

[85.4, 20.0, 12.5]
[85.4, 20.0]
False

Exercise 6: Classify each expense (Part 4)

With amounts = [85.40, 12.50, 42.00, 9.99], loop over the list with for and classify each amount: big if it is 50 or more, medium if it is 15 or more, and small otherwise. Print each amount with its label.

Solution.

amounts = [85.40, 12.50, 42.00, 9.99]

for amount in amounts:
    # The first True wins: the order of the conditions matters
    if amount >= 50:
        label = "big"
    elif amount >= 15:
        label = "medium"
    else:
        label = "small"
    print(amount, label)

Output:

85.4 big
12.5 small
42.0 medium
9.99 small

Exercise 7: Add up and count (Part 4)

With the month's eight amounts, [85.40, 20.00, 12.50, 9.99, 14.30, 42.00, 18.75, 16.00], use a for to compute the total and how many expenses are greater than 20. Show the total with two decimals.

Solution.

amounts = [85.40, 20.00, 12.50, 9.99, 14.30, 42.00, 18.75, 16.00]

total = 0
over_20 = 0
for amount in amounts:
    total = total + amount
    # 20.00 does not count: > means strictly greater
    if amount > 20:
        over_20 = over_20 + 1

print(f"Total: {total:.2f}")
print("Over 20:", over_20)

Output:

Total: 218.94
Over 20: 2

Exercise 8: Indexes and slices (Part 5)

With the same list of eight amounts, show the first three, the last two, how many there are and the highest one.

Solution.

amounts = [85.40, 20.00, 12.50, 9.99, 14.30, 42.00, 18.75, 16.00]

# Indexes start at 0; the end of a slice is not included
print(amounts[:3])
# Negative indexes count from the end
print(amounts[-2:])
print(len(amounts), max(amounts))

Output:

[85.4, 20.0, 12.5]
[18.75, 16.0]
8 85.4

Exercise 9: Totals by category with a dictionary (Part 5)

With rows = [("food", 85.40), ("transport", 20.00), ("food", 12.50), ("home", 9.99)], build a totals dictionary that adds up the amounts of each category.

Solution.

rows = [("food", 85.40), ("transport", 20.00), ("food", 12.50), ("home", 9.99)]

totals = {}
for category, amount in rows:
    # get returns 0 the first time the category shows up
    totals[category] = totals.get(category, 0) + amount

print(totals)

Output:

{'food': 97.9, 'transport': 20.0, 'home': 9.99}

Exercise 10: Your first function (Part 6)

Write the function parse_amount(text) that receives an amount as text, removes the spaces on both sides with strip() and returns the number with float(). Test it with " 85.40 " and add parse_amount("12.50") + parse_amount("20").

Solution.

def parse_amount(text):
    """Turn the text of an amount into a number, without surrounding spaces."""
    return float(text.strip())


print(parse_amount(" 85.40 "))
print(parse_amount("12.50") + parse_amount("20"))

Output:

85.4
32.5

Exercise 11: total_by_category (Part 6)

Write total_by_category(rows): it receives a list of dictionaries with category and amount (the amount as text), uses your parse_amount and returns the dictionary of totals. Test it with these three rows: food 85.40, transport 20.00, food 12.50.

Solution.

def parse_amount(text):
    return float(text.strip())


def total_by_category(rows):
    """Add up the amounts of each category; each row is a dictionary."""
    totals = {}
    for row in rows:
        category = row["category"]
        totals[category] = totals.get(category, 0) + parse_amount(row["amount"])
    return totals


rows = [
    {"category": "food", "amount": "85.40"},
    {"category": "transport", "amount": "20.00"},
    {"category": "food", "amount": "12.50"},
]
print(total_by_category(rows))

Output:

{'food': 97.9, 'transport': 20.0}

Exercise 12: Skip the bad row (Part 7)

With texts = ["85.40", "abc", "12.50"], add up the amounts with a for. Wrap the conversion in try / except ValueError: if a text is not a number, print Skipped: and the text, and move on to the next one.

Solution.

texts = ["85.40", "abc", "12.50"]

total = 0
for text in texts:
    try:
        total = total + float(text)
    except ValueError:
        # Plan B: say which text was skipped and move on to the next one
        print("Skipped:", text)

print(f"Total: {total:.2f}")

Output:

Skipped: abc
Total: 97.90

Exercise 13: Read the expenses file (Part 8)

First run the cell that creates expenses.csv in your Colab (it is already written: just run it). Then, in the next cell, read the file with csv.DictReader, opening it with with open(..., encoding="utf-8", newline=""), and show how many rows it has and the first row.

Before that, the notebook cell creates expenses.csv with %%writefile, a Colab instruction that saves the cell's content as a file.

Solution.

import csv
from pathlib import Path

path = Path("expenses.csv")
# newline="" is what the csv module asks for; utf-8 always explicit
with open(path, encoding="utf-8", newline="") as file:
    rows = list(csv.DictReader(file))

print(len(rows), "rows")
print(rows[0])

Output:

8 rows
{'date': '2026-11-02', 'category': 'food', 'description': 'Groceries', 'amount': '85.40'}

Exercise 14: The full report (Part 9)

Put it all together in one cell: read_rows(path), parse_amount(text), total_by_category(rows) (skipping invalid amounts), print_summary(totals) and save_summary(totals, path), plus a main(path) that calls them in order. Run main("expenses.csv"). In Colab the path goes as a parameter of main: here sys.argv carries Colab's own arguments.

Solution.

"""Summarize the month's expenses by category and save the result to summary.json."""

import csv
import json
from pathlib import Path


def read_rows(path):
    """Read the CSV and return a list of dictionaries, one per row."""
    # with closes the file when the block ends, even if something fails inside
    with open(path, encoding="utf-8", newline="") as file:
        return list(csv.DictReader(file))


def parse_amount(text):
    """Turn the amount text into a number; reject negative amounts."""
    amount = float(text)  # raises ValueError if the text is not a number
    if amount < 0:
        raise ValueError(f"negative amount: {amount}")
    return amount


def total_by_category(rows):
    """Add up the amounts of each category and skip rows with an invalid amount."""
    totals = {}
    for row in rows:
        try:
            amount = parse_amount(row["amount"])
        except ValueError:
            # Plan B: say which row was skipped and move on to the next one
            print(f"Skipped {row['date']}: {row['amount']!r} is not a valid amount")
            continue
        category = row["category"]
        # get returns 0 the first time we see the category
        totals[category] = totals.get(category, 0) + amount
    return totals


def print_summary(totals):
    """Print a table: one line per category and the total at the end."""
    for category, amount in totals.items():
        print(f"{category:<10} {amount:>8.2f}")
    print(f"{'total':<10} {sum(totals.values()):>8.2f}")


def save_summary(totals, path):
    """Save the totals as JSON, rounded to two decimals."""
    rounded = {category: round(amount, 2) for category, amount in totals.items()}
    Path(path).write_text(json.dumps(rounded, indent=2), encoding="utf-8")


def main(path):
    # In Colab the path arrives as a parameter: sys.argv carries Colab's own arguments
    try:
        rows = read_rows(path)
    except FileNotFoundError:
        print(f"File not found: {path}")
        return
    totals = total_by_category(rows)
    print_summary(totals)
    save_summary(totals, "summary.json")
    print(f"Saved summary.json with {len(totals)} categories")


main("expenses.csv")

Output:

food         139.90
transport     34.30
home          28.74
fun           16.00
total        218.94
Saved summary.json with 4 categories