01A.1 Running Python: Programs, the REPL and Syntax Basics

FoundationsLesson 1 of 1113,449 words8 parts
Module 01A · 0 of 11 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11

This is where the path starts: you will install Python, run your first program three different ways, learn to read the error messages Python gives you, and learn the small set of syntax rules that every other lesson in this module builds on. By the end you will be able to write a correct, readable .py file, run it, fix the mistakes it throws at you, and use the interactive interpreter for quick experiments — the same skills you will use in every later module, where all the code is Python.

What you'll learn

  • What Python actually is — interpreted, dynamically typed, strongly typed, garbage-collected and indentation-delimited — and what a program is
  • The four ways to run Python: a script file, python -c, python -m, and the interactive interpreter (the REPL), plus what a notebook is
  • Which Python version to install, how the annual release cycle and end-of-life dates work, and why "Python 2" is gone
  • How to install Python: uv (recommended), the python.org installers, system package managers, and the stdlib venv alternative
  • python vs python3 vs the Windows py launcher, and how to check which interpreter you are really running
  • The anatomy of a first program: files, arguments, __name__ == "__main__" and exit codes
  • The REPL in depth: multiline input, _, help(), dir(), history, exit() and PYTHONSTARTUP
  • Syntax fundamentals: statements vs expressions, indentation, comments and docstrings, naming conventions, keywords, print and input
  • Names, values and types: assignment as naming, id(), is vs ==, dynamic typing, the core types, truthiness, operators and the walrus operator
  • How to read a traceback: SyntaxError, IndentationError, NameError and TypeError, line by line
  • PEP 8 in one page, ruff format, editor setup, and a one-page Python cheat sheet

What you don't need

  • Any programming experience at all. Experienced developers will move faster; the "Coming from another stack" callouts flag the places where your old habits will mislead you.
  • Any API keys, accounts, packages or services. Everything in this lesson is the Python standard library only, offline.
  • Deep knowledge of data structures. Lists and dicts appear in examples as previews; 01A.4 owns them.

Setup

This lesson needs a terminal and a text editor — 00.1 walks through setting both up on macOS, Windows and Linux if you haven't yet — and Python 3.11 or newer (3.13 or newer recommended; see 1.3). No API key needed.

The recommended way to get Python is uv, a fast Python manager from Astral (current release 0.13.x as of November 2026). Install uv itself first, from its official installation page:

bash
# macOS / Linux
curl -LsSf https://astral.sh/uv/install.sh | sh

# Windows (PowerShell)
powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"

(You can also brew install uv, pipx install uv or pip install uv; the docs cover all routes.) Then install Python and check it:

bash
uv python install 3.13
python3 --version    # or: python3.13 --version — see 2.4 for the name trap

Prefer the official installers? Download the macOS or Windows installer from python.org/downloads (on Windows, tick "Add python.exe to PATH"), or use your system's package manager — all covered honestly in Part 2. Full project management with uv (pyproject.toml, lockfiles, virtual environments) is 01B.1; this lesson only needs enough to run a file.


What you must be able to do after this lesson#

  • Install Python with uv and check which interpreter runs
  • Run Python as a script, with python -c, with python -m and in the REPL
  • Write a small program with the main guard and an exit code
  • Explain indentation, statements and expressions
  • Read a basic traceback and fix the error
  • Name variables in the standard Python style

Why this matters for an AI engineer#

Everything you will build in Modules 01B to 14 is Python: calling provider APIs, parsing streamed JSON, validating structured output, writing eval harnesses, deploying services. The language itself is not the hard part — but the habits are: knowing which interpreter your code runs on, reading a traceback instead of guessing, understanding that is is not ==, and being able to try an idea in the REPL in ten seconds instead of writing a file, running it and reading a log.

You'll hear or hit... You'll understand it after...
"Just run it with python3 script.py" Part 3: your first program
"Is it python or python3 on this machine?" 2.4 python vs python3 vs py
"Which Python is this venv/uv actually using?" 2.6 Which interpreter am I running?
"Drop into the REPL and try it" Part 4: the interactive interpreter
"IndentationError: unexpected indent" 5.2 Indentation and 7.2
"NameError: name 'ticket_stauts' is not defined. Did you mean: 'ticket_status'?" 7.4 NameError
"TypeError: can only concatenate str (not \"int\") to str" 7.5 TypeError and 6.9 Type conversion
"Why did x is y come out False when they're equal?" 6.7 == vs is
"Why does 0 or "" behave weirdly in my if?" 6.6 Truthiness
"What's if __name__ == \"__main__\": for?" 3.4 __name__ and the __main__ guard
"The script exited with code 1 — what failed?" 3.5 Exit codes

Part 1: What Python is#

1.1 Five adjectives that describe the whole language#

Python is usually described with five words. Each one changes how you write and debug code, so take thirty seconds on each.

Interpreted. There is no separate compile-then-run step like C or Java. You write a .py file, and the interpreter — the python3 program — reads it and executes it directly. Under the hood CPython first compiles your source into an intermediate form called bytecode, then a loop executes that bytecode instruction by instruction:

flowchart LR
    A["your_file.py<br/>(source code)"] --> B["compiler<br/>(inside the interpreter)"]
    B --> C["bytecode<br/>(compact instructions)"]
    C --> D["interpreter loop<br/>executing instruction by instruction"]
    D --> E(("output / side effects"))

Two consequences you will feel immediately:

  • You can edit a file and re-run it instantly — no build step.
  • Errors can appear while the program is running (a runtime error), not only before it starts. That's why tracebacks exist; Part 7 teaches you to read them.

Dynamically typed. A variable has no declared type. The value carries its type, and the same name can point at a string today and an integer tomorrow:

python
value = "hello"     # value points at a string
value = 42          # now it points at an int — perfectly legal

Strongly typed. Dynamic typing does not mean types don't matter. Python will not silently convert between types for you: "5" + 3 is an error, not "53" or 8. You must convert explicitly — int("5") + 3. (You'll meet this rule again in 6.9 and 7.5.) This is the opposite of JavaScript's "5" + 3 === "53" and PHP's loose comparisons; 01A.11 maps the differences.

Garbage-collected. You never free memory yourself. When no name refers to an object any more, the interpreter reclaims it automatically. The del statement only removes a name; it doesn't guarantee the object disappears if something else still points at it (6.2).

Indentation-delimited. Python has no curly braces. Blocks of code are defined by indentation — leading whitespace:

python
if age >= 18:
    print("adult")      # indented: inside the if
    print("welcome")    # indented: still inside
print("always runs")    # not indented: outside

This single choice is why Python reads like pseudocode — and why 5.2 and mixed tabs/spaces cause more beginner errors than anything else.

1.2 What a program is, and the four ways to run Python#

A program is just a text file of Python instructions plus the data it processes. But "running Python" happens in four distinct modes — plus the notebook format, which is a document rather than a mode — and confusing them causes endless beginner questions:

Mode Where it lives Best for Exit when
Script (python3 file.py) A .py file on disk Anything reusable, shareable, or longer than a few lines The file ends, or sys.exit()/an unhandled error
-c one-liner (python3 -c "...") The command line itself Quick calculations, testing an expression After the statement(s) finish
-m module (python3 -m this) A module from the stdlib or your project Running a package's entry point, python -m pip-style tools Same as a script
REPL (python3 with no arguments) An interactive session in the terminal Experimenting, inspecting values, learning You type exit() or press Ctrl-D
Notebook (Jupyter .ipynb) A document of cells mixing code and prose Exploration, data work, teaching It's a document, not a process — kernels run the cells

The first three are covered in Part 3, the REPL in Part 4. Notebooks deserve one paragraph because you'll meet them: Jupyter notebooks store code in JSON cells you can run one at a time, show output inline, and mix Markdown explanations — excellent for exploring data, dangerous for production code (state hides between cells, diffs are painful, tests are awkward). The AI-engineering path uses plain .py files and uv; notebooks are for your own scratch work. 01B.1 shows uv's Jupyter integration if you want one.

1.3 Versions and which one to install#

Python releases a new feature version roughly every twelve months (an annual October cadence), and each version is supported for about five years: roughly two years of regular bugfix releases, then security-only fixes. As of November 2026 the supported line-up is:

Version Released Status End of support Why it matters to you
3.15 Oct 2026 Bug fixes ~Oct 2031 Newest. lazy import, frozendict, sentinel, UTF-8 default encoding
3.14 Oct 2025 Bug fixes ~Oct 2030 t-strings, deferred annotations, free-threaded officially supported
3.13 Oct 2024 Security fixes ~Oct 2029 The new REPL, colour tracebacks, better error suggestions — recommended floor for this path's examples
3.12 Oct 2023 Security fixes ~Oct 2028 type statement, improved f-strings, itertools.batched
3.11 Oct 2022 Security fixes ~Oct 2027 Oldest supported. Fine-grained traceback locations, ExceptionGroup, tomllib, first faster CPython
3.10 Oct 2021 End of life Oct 2026 — match/case, better errors; no longer receives fixes

(Sources: python.org downloads and the developer guide's version status, checked November 2026. Schedules can shift slightly — always check there for the current dates.)

Three practical rules fall out of this table:

  1. Install 3.13 or newer if you can. This path's examples are written for 3.11+, and 3.13's REPL and coloured tracebacks make learning noticeably nicer. Everything shown works on 3.11 too; where a feature needs 3.12, 3.13, 3.14 or 3.15 the lesson says so and shows the older alternative.
  2. Don't install 3.10 or older. 3.10 hit end of life in October 2026 and gets no more fixes; anything older is long dead.
  3. Check what you actually have before assuming — python3 --version. Distros and old machines love to hide an ancient Python behind the python3 name (2.4 shows how to be sure).

Why "Python 2" is gone

If you see old tutorials, print "hello" (no parentheses) is the giveaway: that's Python 2, whose final release was 2.7 in 2010 and whose end-of-life was 1 January 2020. For a decade the community was split between maintaining Python 2 compatibility and moving on; the automated 2to3 migration never worked well enough, so adoption crawled until libraries dropped 2 and the dam broke. Today Python 2 receives no fixes, and its syntax is simply invalid:

text
$ python3 py2_style.py
  File "py2_style.py", line 2
    print "hello world"
    ^^^^^^^^^^^^^^^^^^^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print(...)?

(Real output from this lesson's scratch run; 7.3 dissects it.) Any tutorial that doesn't say "Python 3" and shows print without parentheses is old enough to be dangerous — close the tab.

1.4 The mental model to keep#

Hold onto five pictures and the rest of the module slots into place:

  • A .py file is a recipe; the interpreter is the cook that reads it top to bottom.
  • Names are labels stuck on objects, not boxes that hold them (6.1).
  • Types belong to values, not variables — but Python won't mix them silently.
  • Whitespace is meaningful: indentation defines blocks.
  • Errors are messages, not verdicts: every traceback names the file, line, and usually the exact expression that failed.

Part 2: Getting Python and running your first program#

uv is the tool this path standardises on: one binary that installs Python versions, runs scripts and manages projects. It exists because the old python + pip + venv dance had too many ways to go wrong. Two commands cover everything this lesson needs:

bash
uv python install 3.13   # download and manage a Python 3.13
uv run script.py         # run a file with the right interpreter

Under the hood, uv python install fetches a CPython build produced by the python-build-standalone project — not an official python.org binary, because Python doesn't publish official binaries for every platform. These builds are what uv and most modern tooling use; they behave identically for everything in this path.

2.2 The python.org installers#

The official route: python.org/downloads offers signed installers for macOS, Windows and source builds. A few honest notes:

  • Windows: the installer has an "Add python.exe to PATH" checkbox at the bottom of the first screen — tick it, or python won't be found from a fresh terminal. (Newer downloads point you at the Windows "install manager" app instead of the classic .exe; both work — follow python.org's current page.) The same installer provides the py launcher covered in 2.4.
  • macOS: the .pkg installer puts python3 on your PATH. Note that macOS also ships a stub python3 (part of the Xcode command-line tools) — if python3 --version reports something odd like 3.9.x, you found the stub; install the real one and check again.
  • Linux: python.org doesn't ship distro packages; see 2.3.

2.3 System package managers and Homebrew#

Every route works; each has a trade-off:

Route Command (examples) Trade-off
Homebrew (macOS) brew install python → python3 (e.g. python3.15) Always recent — 3.15.x as of November 2026; python3 is provided, bare python needs a PATH tweak
apt (Debian/Ubuntu) sudo apt install python3 python3-venv Convenient but lags: Ubuntu LTS may ship a Python that's already old — always python3 --version afterwards
dnf / zypper (Fedora / openSUSE) sudo dnf install python3 Similar lag; often fine
uv uv python install 3.13 Latest patch releases, zero PATH pollution, per-project versions — the recommended route
python.org download installer Official binaries; you manage updates yourself

The stdlib fallback: python3 -m venv. If Python is already installed, you don't need uv or an installer at all — the standard library ships a module that builds an isolated virtual environment: a private copy of the interpreter plus its own site-packages, so project dependencies never tangle with your system Python:

bash
python3 -m venv .venv
source .venv/bin/activate        # macOS / Linux
.venv\Scripts\Activate.ps1       # Windows PowerShell
python --version                 # now runs the venv's interpreter
which python                      # ...inside .venv/bin (or .venv\Scripts)
deactivate                       # leave the environment

(On Debian/Ubuntu the venv module needs the python3-venv package — that's why it appears in the apt row above; the python.org and Homebrew installs include it.) A venv answers "which packages does this project have?" — 01B.1 covers environments properly, and uv just makes the same idea painless (uv run creates and syncs one for you automatically). For this lesson, plain python3 file.py is all you need.

2.4 python vs python3 vs py#

Three names, one interpreter, and the confusion is entirely historical:

  • python3 — the conventional name on macOS and Linux for "the Python 3 interpreter". During the Python 2→3 transition, systems needed both, so distros added python3 alongside python (which meant Python 2). Today python increasingly means Python 3 too, but not always — on many systems python doesn't exist at all, or still points at something ancient.
  • python — on Windows, the python.org installer puts python.exe on PATH, so python works. On macOS/Linux it may be missing, an alias, or a different version than python3. This path writes python3 everywhere because it's unambiguous on POSIX systems; on Windows python is fine — just be consistent and check --version.
  • py — the Python launcher for Windows (installed by the python.org installer). py -3.13 script.py, py -0 to list installed versions, py -m pip .... It exists so Windows can juggle multiple Python versions cleanly. macOS/Linux have no py; use python3 or a versioned name like python3.13.

The deeper truth: the name you type doesn't tell you which interpreter ran — three different installs can all answer to python3 in different terminals. That's why 2.6 exists.

2.5 Your first run#

Create a file called hello.py in a folder you made for this lesson (e.g. ~/code/ai_engineer_roadmap-lessons/01a/ — anywhere tidy works):

python
# hello.py — your first Python program
print("Hello, world!")

Then, from that folder in your terminal:

bash
python3 hello.py
Output1 line
Hello, world!

That's it — a complete program is one line. Everything else in this lesson is about doing it well: naming things clearly, handling the cases where the simple version breaks, and knowing what to do when Python pushes back.

2.6 Which interpreter am I running?#

When code "works on my machine" but not yours, the first question is always which Python executed it? Ask the interpreter itself:

python
# whichpy.py
import sys

print("executable:", sys.executable)
print("version:  ", sys.version.split()[0])
print("prefix:   ", sys.prefix)
Example output · illustrative3 lines
executable: /opt/homebrew/opt/python@3.14/bin/python3.14
version:   3.14.6
prefix:    /opt/homebrew/opt/python@3.14/Frameworks/Python.framework/Versions/3.14
  • sys.executable is the exact binary that is running your code — the single most useful fact when debugging "wrong Python" problems. Inside a virtual environment or uv run it points inside that environment.
  • sys.version is a multi-line string describing the exact build; .split()[0] grabs just 3.14.6. (sys.version_info gives it as numbers — (3, 14, 6) — if you ever need to compare versions programmatically, e.g. sys.version_info >= (3, 13).)
  • sys.prefix tells you which installation/environment the interpreter belongs to.

A faster check from the shell, no file needed:

bash
python3 -VV        # version plus compiler/build details
python3 -c "import sys; print(sys.executable)"

Part 3: Your first program#

3.1 Running a file: python3 file.py#

Everything in a .py file runs top to bottom, once, when you invoke it. Comments start with # and are ignored by the interpreter — they exist for humans:

python
# tickets_report.py — count tickets by hand for now
tickets = [
    {"id": 1, "subject": "login broken", "status": "open"},
    {"id": 2, "subject": "slow export", "status": "closed"},
    {"id": 3, "subject": "billing question", "status": "open"},
]

open_count = 0
for ticket in tickets:
    if ticket["status"] == "open":
        open_count += 1

print("Total tickets:", len(tickets))
print("Open tickets:", open_count)
Output2 lines
Total tickets: 3
Open tickets: 2

Don't worry about understanding every line yet — for loops are 01A.3, lists and dicts are 01A.4. Notice the shape: data at the top, work in the middle, output at the bottom. That skeleton is most of the scripts you'll ever write.

It helps to know what the interpreter just did with that file. When you run python3 tickets_report.py, CPython reads the whole file and compiles it to bytecode before executing a single line — which is why a SyntaxError or TabError anywhere in the file stops everything, even lines that look fine (that's the "compile-time vs runtime" split 7.1 formalises). Then it executes the bytecode top to bottom, once, and exits with code 0 — or 1 if an exception escaped. Imported modules get their bytecode cached in a __pycache__/ folder next to them so the next run starts faster; you can ignore (or delete) it safely — 01A.7 explains the machinery.

3.2 python -c: the one-liner#

For a quick calculation or a sanity check, skip the file entirely:

bash
python3 -c "print(6 * 7)"
python3 -c "import sys; print(sys.version.split()[0])"
Output1 line
42
Example output · illustrative1 line
3.14.6

Rules of -c: the code is a single argument (quote it carefully — see the shell note in 3.6), it can contain multiple statements separated by ; or newlines, and sys.argv inside it looks slightly different (sys.argv[0] is '-c'). Perfect for "does int('3.5') work?" moments — which is exactly what the REPL is also for, and usually nicer.

3.3 python -m: running a module#

-m runs a module — a file of Python that lives on the import path — as if it were a program:

bash
python3 -m this        # prints the Zen of Python (a stdlib module that prints on import)
python3 -m json.tool   # a real stdlib tool: pretty-prints JSON from stdin
Output21 lines
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

The this module's whole job is to print those nineteen lines when executed — a charming proof that -m runs any module, not just ones designed as programs. In your own projects, -m is how you run packages: python -m triage runs triage/__main__.py (01A.7 owns packages and __main__.py). You'll also see python -m pip, python -m pytest, python -m uvicorn — the standard way tools expose CLI entry points.

3.4 __name__ and the __main__ guard#

Every Python file, when it runs, has a built-in variable called __name__. Its value depends on how the file was started:

  • Run directly (python3 showname.py) → __name__ is '__main__'
  • Imported by another file (import showname) → __name__ is the module's name, e.g. 'showname'
python
# showname.py
print("__name__ is:", __name__)
bash
python3 showname.py
Output1 line
__name__ is: __main__
pycon
>>> import showname
__name__ is: showname

The famous idiom builds on this:

python
# tool.py
def main():
    print("Running the tool")

if __name__ == "__main__":
    main()

if __name__ == "__main__": means "only do this when the file is run directly, not when something else imports it." It's how a file can be both a runnable program and a library other files reuse: the functions are always available to importers, but the "go" code only fires on a direct run. You'll write this guard in almost every script from 01A.9 onwards; 01A.7 explains the machinery fully.

3.5 Exit codes#

When a program finishes — successfully or not — it returns an integer exit code to the shell: 0 means success, anything else means failure (conventionally 1 for a generic error, 2 for misuse). The shell stores it in $? (bash/zsh) or $LASTEXITCODE (PowerShell):

python
# exit3.py
import sys
sys.exit(3)        # end the program now, with exit code 3
console
$ python3 exit3.py
$ echo $?
3
python
# fail.py — SystemExit with a message prints it, then exits 1
raise SystemExit("something went wrong")
console
$ python3 fail.py
something went wrong
$ echo $?
1

Why care? Because exit codes are how scripts talk to other scripts. cmd1 && cmd2 runs cmd2 only if cmd1 exited 0; CI pipelines, cron jobs and Makefiles all branch on them. An unhandled Python exception exits with code 1 automatically — which is why "the traceback printed" and "exit code 1" are the same event. (sys.exit() with no argument exits 0; sys.exit("msg") prints msg and exits 1.)

3.6 A note on quotes and shells#

Three programs meet when you type a command: your shell (bash/zsh/PowerShell), the Python interpreter, and your text editor. Each has its own quoting rules, and the classic beginner bug is a quote collision:

bash
# Works: double quotes outside, single inside
python3 -c "print('hello')"

# Breaks on bash: the inner double quotes end the argument early
python3 -c "print("hello")"

The fix is matching quote styles ('...' inside "..."), escaping (\"), or — better — putting the code in a file where quoting stops mattering. This is also why the REPL exists: no shell quoting at all.

3.7 Command-line arguments: sys.argv#

A script can receive extra words from the command line. They arrive as the list sys.argv (argument vector) in the sys module:

python
# args_demo.py
import sys

print("argv:", sys.argv)
print("script:", sys.argv[0])
print("arguments:", sys.argv[1:])
print("count:", len(sys.argv) - 1)
bash
python3 args_demo.py Ada "Grace Hopper" 42
python3 args_demo.py
Output8 lines
argv: ['args_demo.py', 'Ada', 'Grace Hopper', '42']
script: args_demo.py
arguments: ['Ada', 'Grace Hopper', '42']
count: 3
argv: ['args_demo.py']
script: args_demo.py
arguments: []
count: 0

Four facts to remember:

  • sys.argv[0] is the script's own name (for -c it is '-c'), so the arguments you typed are sys.argv[1:]. With no extra words the list has exactly one item.
  • Every argument is a str, even 42 — the same rule as input() (5.7). Convert with int() or float() before doing arithmetic.
  • The shell splits the line into words, not Python. Quote an argument that contains spaces ("Grace Hopper" is one item; unquoted it would be two). The quoting rules of 3.6 apply.
  • Indexing a missing argument raises IndexError (sys.argv[1] with no arguments), so check len(sys.argv) first or slice, as the classify_ticket example at the end of 5.8 does.

For anything beyond one or two positional words (flags like --verbose, --help text, validation), use the standard library's argparse, which 01A.7 introduces; uv run script.py Ada passes arguments through in exactly the same way.


Part 4: The interactive interpreter (the REPL)#

4.1 What the REPL is#

Type python3 with no arguments and you get the REPL — the Read-Eval-Print Loop:

bash
python3
Example output · illustrative3 lines
Python 3.14.6 (main, Jun 10 2026, 10:03:53) [Clang 21.0.0 (clang-2100.0.123.102)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>

The >>> is the prompt: type an expression or statement, press Enter, and the interpreter evaluates it, prints the result (for expressions), and shows a fresh prompt. No file, no saving, no shell quoting — the fastest way to answer "what does int('3.5') do?" or "is 'a' * 3 'aaa'?". Every example in this module that shows >>> is a REPL session you can reproduce by typing the lines yourself.

4.2 The REPL you get on 3.13+#

If you're on Python 3.13 or newer, the REPL is a ground-up rewrite (borrowed from the PyPy project) and noticeably nicer:

  • Multiline editing — type def f():, press Enter, and you get a ... continuation prompt for the body; blank line finishes the block.
  • History — Up/Down arrows recall previous lines (persisted across sessions in ~/.python_history on POSIX).
  • Colour — prompts, results and tracebacks are colourised on a terminal; disable with NO_COLOR=1 or PYTHON_COLORS=0.
  • REPL commands — help, exit, quit, copyright, credits, license work as bare words.
  • F2 history search, F1 help — discoverable by typing help at the prompt.

On 3.11/3.12 you get the classic REPL: same >>>/... prompts if readline is available, plainer output. Everything in this lesson works on both; the transcripts show the modern one.

A genuine session (verified on Python 3.14):

pycon
>>> def greet(name):
...     return "hi " + name
...
>>> greet("Ada")
'hi Ada'
>>> x = 21
>>> x * 2
42
>>> _ + 1
43
>>> exit()

Notice the details:

  • def greet(name): opened a block — the ... prompt means "still inside the block". A blank line at ... closed it and the function was defined (no output = success for statements).
  • x = 21 printed nothing: assignment is a statement, not an expression — it produces no value to display.
  • x * 2 is an expression: its value 42 was printed automatically.
  • _ holds the last printed value: after 42, _ + 1 was 43.
  • exit() ends the session — and it works everywhere. The finer detail: on 3.13+ exit, quit, help, copyright, credits and license are also REPL commands, so on a real terminal the bare word exit closes the session and bare help opens the interactive help browser. But when input is piped (or you're on the classic ≤3.12 REPL) those names are just helper objects, and bare exit only prints the hint Use exit() or Ctrl-D (i.e. EOF) to exit — so exit() is the form that behaves identically in every mode.

4.3 REPL tools: _, help(), dir(), exit()#

  • _ (underscore) — the result of the last expression. Great for chaining: len("hello") → 5, then _* 2 → 10.
  • help() — interactive help browser (type help alone on 3.13+, or help(len) for one topic). Shows docstrings, signatures, and "Help on..." pages. Also available in scripts, but the REPL is where it shines.
  • dir() — lists names currently defined. In a fresh REPL it's just the dunders:
pycon
>>> dir()
['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']
  • exit() / quit() — end the session. On 3.13+ the bare words exit, quit, help, copyright, credits and license are REPL commands on a real terminal; the callable objects behind them come from the site module, and Ctrl-D on an empty prompt does the same on POSIX (Ctrl-Z then Enter on Windows).
  • copyright, credits, license — Easter eggs that show the licence text (in a scrollable pager on 3.13+).
pycon
>>> help(len)
Help on built-in function len in module builtins:

len(obj, /)
    Return the number of items in a container.

4.4 PYTHONSTARTUP: a file that runs at every REPL launch#

If the environment variable PYTHONSTARTUP points at a .py file, the interpreter executes it when the REPL starts (only in interactive mode — never for scripts, a deliberate safety choice). It's the idiomatic place for personal helpers:

python
# ~/.python_startup.py  (whatever path you choose)
import this            # prints the Zen every time — or import your own helpers
def tickets(n):
    return [{"id": i, "status": "open"} for i in range(n)]
bash
export PYTHONSTARTUP=~/.python_startup.py   # add to ~/.zshrc / ~/.bashrc once
python3
powershell
$env:PYTHONSTARTUP = "$HOME\.python_startup.py"   # this session only
[Environment]::SetEnvironmentVariable("PYTHONSTARTUP", "$HOME\.python_startup.py", "User")   # persistent (or System > Environment Variables)

Verified locally: a startup file defining STARTUP_LOADED = True made >>> STARTUP_LOADED print True on the next line. Keep it small — it's for conveniences, not real code.

4.5 IPython and Jupyter: the REPL's cousins#

You'll hear two names constantly in data/AI work:

  • IPython — a richer REPL (better tracebacks, %magic commands, object inspection). uvx --from ipython ipython or pip install ipython gives you ipython. Everything here works identically.
  • Jupyter — the notebook ecosystem (IPython kernel + browser UI). Covered in 1.2: fine for exploration, not for the code in this path.

4.6 -i: run a script, then keep the REPL#

The -i flag combines a normal run with a REPL afterwards: the file executes, then you land at a >>> prompt with the script's names still defined. It's the standard debugging loop — run, inspect the state, tweak, re-run:

python
# counter.py — a tiny script worth inspecting afterwards
total = 0
for n in range(1, 6):
    total += n

print("total:", total)
console
$ python3 -i counter.py
total: 15
>>> total
15
>>> n
5
>>> exit()

Notice n — even the loop variable survives, because it was just a normal name binding. -i works after -c and -m too: python3 -i -c "x = 41" lands you at a prompt where x is already 41. Handy when a one-liner grows teeth — build the value inline, then poke at it interactively before committing to a file.


Part 5: Syntax fundamentals#

Syntax is the set of rules for form — what a valid Python file looks like before it means anything. Five rules cover 95% of what beginners trip on.

5.1 Statements vs expressions#

  • An expression produces a value: 2 + 3, len("hi"), x, "a" * 3.
  • A statement does something: x = 2 + 3, print("hi"), import sys, if ...:.

The practical differences you'll feel:

  • Only expressions get their value auto-printed in the REPL (>>> 2 + 3 → 5; >>> x = 5 → nothing).
  • Some places only accept expressions — e.g. the right side of =, inside f(...) — and a bare statement there is a SyntaxError.
  • print(...) is a function call (an expression that returns None), not a language keyword like in Python 2 — you can pass it around, though you rarely should.

5.2 Indentation: the rule that defines Python#

Blocks are marked by consistent leading whitespace. The conventions that keep you out of trouble:

  • 4 spaces per level is the standard (PEP 8). Two is legal; eight is legal; inconsistent is not.
  • Never mix tabs and spaces in the same file — Python 3 refuses to guess what such indentation means: when a block's structure would depend on how wide a tab is, it raises TabError rather than risk running the wrong code. Configure your editor to insert spaces on Tab (every editor does this by default for Python; 8.3 shows where in VS Code — the status-bar indentation indicator toggles it in any editor).
  • Indentation must be consistent within a block, but sibling blocks may align however they like as long as each block is internally consistent.
  • Blank lines and comments may appear anywhere; they don't affect indentation.
python
def classify(score):
    if score >= 90:
        return "A"
    elif score >= 80:      # same level as 'if' — a sibling branch
        return "B"
    else:
        return "C"

result = classify(85)     # back to zero indent — outside the function

The classic failure — a stray indent with no open block:

pycon
>>> x = 1
>>>     y = 2
  File "<stdin>", line 1
    y = 2
IndentationError: unexpected indent

(Real output with the lines piped in; 7.2 dissects it. In the interactive 3.13+ REPL the file name reads <python-input-0> for your first input, <python-input-1> for the next and so on, instead of <stdin>; checked on 3.14.) And the subtler one — tabs where spaces were expected:

text
# mixed_indent.py — note the TAB before print("done")
def greet(name):
    if name:
        print("hi", name)
\tprint("done")
Example output · illustrative4 lines
  File "/Users/you/.../mixed_indent.py", line 4
    	print("done")
    ^
TabError: inconsistent use of tabs and spaces in indentation

TabError is a subclass of IndentationError, which is a subclass of SyntaxError — all raised before a single line runs, because Python parses the whole file first. (The path shown is absolute since Python 3.9 and differs per machine; the message and caret are verbatim.)

5.3 Line continuation, comments and docstrings#

Three ways to handle long lines:

python
# 1. Implicit continuation inside brackets — preferred
total = (
    price * quantity
    + tax
)

# 2. Explicit backslash (rarely needed; easy to break with trailing spaces)
path = "some/very/long/" \
       "path/here"

# 3. Just let the formatter wrap it — ruff format handles 88-char lines
total = price * quantity + tax + shipping + handling_fee + discount

Comments start with # and run to end of line. Use them for the why, not the what:

python
open_count = 0
for ticket in tickets:
    # status is stored lowercase by the import; compare defensively anyway
    if ticket["status"].lower() == "open":
        open_count += 1

Docstrings are string literals as the first statement of a module, function or class — they document the thing to help() and to readers:

python
def classify_ticket(text):
    """Return 'billing', 'bug' or 'other' for a ticket's subject line."""
    ...
pycon
>>> help(classify_ticket)
Help on function classify_ticket in module __main__:

classify_ticket(text)
    Return 'billing', 'bug' or 'other' for a ticket's subject line.

One-line docstrings use """..."""; multi-line ones put the summary on the first line, a blank line, then details. 01A.3 covers docstring conventions (Google/NumPy style) properly.

5.4 Identifiers and naming conventions#

An identifier names a variable, function, class or module. Rules: start with a letter or _, continue with letters, digits and _; can't be a keyword; case-sensitive (Total ≠ total). Unicode letters are legal (café = 1 works) but rare in practice — stick to ASCII.

The conventions (PEP 8) that make Python code instantly readable:

Convention Used for Example
snake_case variables, functions, modules open_ticket_count
PascalCase (CapWords) classes TicketStore
UPPER_CASE constants — values meant never to change MAX_RETRIES = 3
_leading_underscore "internal use" — a convention, not enforcement _cache, _helper()
__dunder__ language-defined names __name__, __init__

5.5 Keywords and reserved words#

Keywords are the ~35 words the grammar owns — you can't use them as names. The authoritative list is data, not memory:

bash
python3 -c "import keyword; print(keyword.kwlist)"
text
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break',
 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for',
 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or',
 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

(35 keywords on Python 3.14; match/case are soft keywords — only reserved in match statements — and type joined them as a soft keyword in 3.12. keyword.softkwlist on 3.14 is ['_', 'case', 'match', 'type']: _ has been a soft keyword since 3.10 as the wildcard in match patterns, and lazy joins the list in 3.15.) Trying class = 5 gives a SyntaxError with the caret under class. New keywords appear occasionally (async/await in 3.7, match/case soft in 3.10, type soft in 3.12, lazy soft in 3.15) — that's why keyword.kwlist exists: ask, don't memorise.

5.6 Shadowing builtins#

Python's builtins (print, len, str, list, id, input, max...) are names every file can use without importing. Nothing stops you redefining them — but everything downstream breaks confusingly:

python
len = 5            # legal! now len(...) is broken in this file
print(len("abc"))  # TypeError: 'int' object is not callable

The name len now points at 5, not the function. The fix is trivial — pick another name (length, n) — but the bug it causes surfaces far from the cause, which is why linters flag it (ruff rule A001/A002, 8.2). Rule of thumb: never assign to a builtin name; if you must shadow deliberately (rare), do it locally inside a function.

5.7 print and input#

print() is how programs talk to humans; input() is how they ask questions. Both are builtins, both worth knowing precisely:

python
# print_demo.py
import sys

print("a", "b", "c")                  # sep=' ' by default
print("a", "b", "c", sep="|")        # custom separator
print("no newline", end="")          # end='' suppresses the newline
print(" <- joined")
print("warning!", file=sys.stderr)   # write to stderr, not stdout
Example output · illustrative4 lines
a b c
a|b|c
no newline <- joined
warning!

(The warning! line appears first on some terminals because stderr is unbuffered while stdout is buffered when piped — stream ordering is a real topic; 01A.8 covers it.)

print returns None — it does something (side effect), it doesn't produce a value. sep, end and file are keyword arguments; flush=True forces immediate output (needed for progress indicators and input() prompts on some platforms).

python
# greet_io.py
name = input("Your name: ")          # writes the prompt, reads a line, strips \n
age_text = input("Your age: ")
age = int(age_text)                  # input() ALWAYS returns str — convert!
print("Hello,", name + "!", "Next year you'll be", age + 1)
console
$ printf 'Ada\n30\n' | python3 greet_io.py
Your name: Your age: Hello, Ada! Next year you'll be 31

Two facts to burn in: input() always returns a str — even if you type 30, you get "30", and "30" + 1 is the TypeError of 7.5; and the prompt has no automatic newline, which is why Your name: Your age: run together above.

5.8 Blank lines and overall layout#

PEP 8's layout rules that matter on day one:

  • Two blank lines between top-level functions/classes; one between methods.
  • One blank line between logical sections inside a function.
  • Files start with imports, then constants, then functions/classes, then the "main" code (often under the __main__ guard from 3.4).
  • Lines ≤ 88 characters (the ruff format default; PEP 8 says 79 but the ecosystem settled on 88 — 8.2).
python
import sys

MAX_RETRIES = 3


def classify_ticket(text):
    """Return a category for a ticket's subject."""
    lowered = text.lower()
    if "bill" in lowered or "invoice" in lowered or "payment" in lowered:
        return "billing"
    if "crash" in lowered or "error" in lowered or "broken" in lowered:
        return "bug"
    return "other"


if __name__ == "__main__":
    print(classify_ticket(sys.argv[1] if len(sys.argv) > 1 else "help"))

Part 6: Names, values and types#

This is the conceptual core of the lesson — and of Python itself. Everything else in the module assumes you think about code this way.

6.1 Assignment: names, not boxes#

The single most important mental correction for newcomers: = does not put a value into a variable. It sticks a name onto an object.

python
x = 10        # the int object 10 gets a new name label: x
y = x         # y is another label on the SAME object
x = 20        # x is re-labelled onto a NEW object; y still points at 10

Verify it:

pycon
>>> x = 10
>>> y = x
>>> x is y        # 'is' asks: same object?
True
>>> x = 20
>>> x is y
False
>>> y
10

There is no "box" that x emptied and refilled — y never had anything to do with x's box, because there was never a box. There were always just objects and names pointing at them. This one picture explains aliasing, mutable-default-argument bugs, function arguments, del, and half the "weird Python" stories you'll hear.

id() shows the object's identity as a number — handy for seeing the model, useless for logic (ids can be reused after an object dies):

pycon
>>> a = [1, 2]
>>> b = a
>>> id(a) == id(b)     # same object -> same id
True
>>> a.append(3)
>>> b                  # b sees it too — same object
[1, 2, 3]

6.2 Assignment, rebinding, aliasing, del#

The full toolkit of name operations:

python
# Chained assignment: ONE object, several names
a = b = [1, 2, 3]
a.append(4)
print(a, b)            # [1, 2, 3, 4] [1, 2, 3, 4] — same list!

# Multiple assignment (unpacking): names on the left, values on the right
first, second = "ab"
print(first, second)   # a b

# Swapping without a temporary
left, right = 1, 2
left, right = right, left
print(left, right)     # 2 1

# del removes a NAME (the object survives if other names point at it)
del left
print(right)           # 1 — unaffected
Output4 lines
[1, 2, 3, 4] [1, 2, 3, 4]
a b
2 1
1
python
def add_tag(tags, new):
    tags.append(new)          # mutates the CALLER's list — no copy made
    return tags

def add_tag_safe(tags, new):
    return tags + [new]       # builds a NEW list; caller's list untouched

When you pass a list to a function, the function gets a name for the same object — not a copy. Mutating it inside affects the caller's data. Whether that's a bug or a feature depends on intent; 01A.4 teaches copying (list(x), x.copy(), copy.deepcopy) and when each is right.

6.3 Dynamic typing: type() and isinstance()#

Because types live on values, you can ask any value what it is:

python
samples = [42, 3.14, True, "hello", None, [1, 2, 3], {"a": 1}]
for value in samples:
    print(value, "->", type(value))
Output7 lines
42 -> <class 'int'>
3.14 -> <class 'float'>
True -> <class 'bool'>
hello -> <class 'str'>
None -> <class 'NoneType'>
[1, 2, 3] -> <class 'list'>
{'a': 1} -> <class 'dict'>

type(x) returns the class of the value; isinstance(x, T) is the everyday check:

python
isinstance(42, int)            # True
isinstance(True, int)          # True! bool IS an int subclass (True == 1)
isinstance(42, (int, float))   # True — a tuple means "any of these"
isinstance("42", int)          # False — it's a string that looks like a number

Prefer isinstance over type(x) == int — it respects inheritance (01A.6 explains why that matters).

6.4 The core types at a glance#

You need five types this lesson; the rest arrive in 01A.4 and 01A.6:

Type Examples Key facts
int 42, -7, 1_000_000 Arbitrary precision — 10**100 works fine; underscores allowed for readability
float 3.14, -0.5, 1e10 IEEE-754 double; / always yields float; 0.1 + 0.2 surprises live in 01A.2
bool True, False Subclass of int: True == 1, True + True == 2
str "hello", 'it\'s', """multi\nline""" Immutable sequence of characters; deep dive in 01A.2
None None The singleton "nothing here"; type is NoneType; check with is None

Two previews worth internalising now:

  • 10**100 really does work — Python integers don't overflow:
pycon
>>> 10**30
1000000000000000000000000000000
>>> type(10**30)
<class 'int'>
  • None is not 0, not "", not False — it's its own thing, and x is None is the only correct way to test for it (6.7).

6.5 Mutable vs immutable — the first look#

Types divide into two camps, and the difference is the aliasing story from 6.2:

Immutable (can't change in place) Mutable (can change in place)
int, float, bool, str, tuple, frozenset, None list, dict, set, bytearray

"Immutable" means operations never modify the object — they produce a new object and rebind the name:

python
s = "hello"
t = s
s += "!"               # NOT s.append — strings can't change; s is re-bound
print(s, t)            # hello! hello
print(s is t)          # False — different objects now

items = [1, 2]
other = items
items.append(3)        # lists CAN change in place — same object
print(items, other)    # [1, 2, 3] [1, 2, 3]
print(items is other)  # True — still the same object
Output4 lines
hello! hello
False
[1, 2, 3] [1, 2, 3]
True

Why it matters beyond curiosity: immutables can be shared safely (no copy needed — nothing can change under you), and they're hashable — usable as dictionary keys and set members, which is how Python implements fast lookups. 01A.4 makes this rigorous; for now just notice that s += "!" looked like mutation but was really rebinding, while items.append(3) genuinely mutated.

6.6 Truthiness and falsiness#

Every value has a truth value: bool(x) answers "would if x: take the branch?". The falsy values are a short, memorizable list:

python
falsy = [0, 0.0, "", [], {}, (), set(), None, False]
truthy = [1, -1, 0.1, " ", "0", [0], {"a": 0}, (0,), {0}, True]
for value in falsy + truthy:
    print(repr(value), "->", bool(value))
Output19 lines
0 -> False
0.0 -> False
'' -> False
[] -> False
{} -> False
() -> False
set() -> False
None -> False
False -> False
1 -> True
-1 -> True
0.1 -> True
' ' -> True
'0' -> True
[0] -> True
{'a': 0} -> True
(0,) -> True
{0} -> True
True -> True

The rules in one breath: zero numbers, empty strings, empty containers and None are falsy; everything else is truthy. The traps:

  • "0" and " " are truthy — non-empty strings, even ones that look like nothing.
  • [0] and {"a": 0} are truthy — a container with anything inside counts, even falsy contents.
  • if items: means "if items is non-empty" — the Pythonic emptiness test. if items is not None: is different: it tests existence, not emptiness. Choosing wrong is a classic bug (if count: silently skips a perfectly valid count of 0; if items is not None: happily lets an empty list through to code that assumed at least one element).

6.7 == vs is#

  • == asks "do these values compare equal?" — uses each type's equality rule.
  • is asks "are these the same object?" — identity, not value.
python
print(1000 == 1000)              # True — same value
print(1000 is 1000)              # True here only because it's literally the same constant

big1 = int("7001000")            # built at run time -> fresh object
big2 = int("7001000")
print(big1 == big2)              # True
print(big1 is big2)              # False — equal values, different objects

s1 = "hello"
s2 = "".join(["hel", "lo"])
print(s1 == s2, s1 is s2)        # True False

value = None
print(value is None)             # True — THE correct None test
Example output · illustrative6 lines
True
True
True
False
True False
True

(One wrinkle visible above: 1000 is 1000 is True and Python prints a SyntaxWarning: "is" with 'int' literal. Did you mean "=="? — the compiler literally warns you. Identical literals share one constant object, which is why it "works"; it's still meaningless.)

The rules:

  • is is for singletons and identity: None, True, False, and occasionally "is this the exact same object I passed in?" (rare — 01A.4 covers the legit uses).
  • == is for values: everything else.
  • Never write if x is "open": or if x is 0: — it may appear to work (small-int caching, string interning) until it doesn't, on another machine, for another value. Linters flag it.

6.8 Operators#

The full tour, grouped by job:

python
# Arithmetic — note / is true division, // floors, % is remainder
print(7 + 3, 7 - 3, 7 * 3, 7 / 3)   # 10 4 21 2.3333333333333335
print(7 // 3, 7 % 3, 7 ** 2)         # 2 1 49  (floor div, remainder, power)
print(-7 // 3, -7 % 3)               # -3 2   (floor rounds toward -inf)

# Comparison — chainable
print(1 < 2 <= 3)                    # True: means 1<2 and 2<=3

# Membership
print("ell" in "hello", "z" not in "hello")   # True True

# Logic — and/or return an OPERAND, not a bool
print(0 or "fallback")               # 'fallback'  (0 is falsy -> right side)
print("" or [])                      # []
print(5 and 10)                      # 10         (5 truthy -> right side)
print(None and 10)                   # None       (short-circuit: right never runs)
print(not 0, not "", not [], not None)  # True True True True

# Bitwise — rare in app code, worth recognising
print(0b1100 & 0b1010, 0b1100 | 0b1010, 0b1100 ^ 0b1010)  # 8 14 6
Output11 lines
10 4 21 2.3333333333333335
2 1 49
-3 2
True
True True
fallback
[]
10
None
True True True True
8 14 6

Two subtleties worth keeping:

  • and/or are not boolean operators — they return one of their operands (or returns the first truthy operand, or the last one if none is truthy; and returns the first falsy operand, or the last one if none is falsy). x or "default" is the idiomatic "default if missing"; a and b() is "call b() only if a is truthy" (short-circuit). They'll matter constantly in 01A.3.
  • // floors toward negative infinity, so -7 // 3 == -3 and -7 % 3 == 2 — the remainder takes the sign of the divisor. 01A.2 covers why this is the right design.

6.9 Type conversion and duck typing#

Conversion is explicit via type-name calls:

python
print(int("42"))        # 42          (strips whitespace, accepts +/- and _)
print(int("1_000"))     # 1000
print(float("3.5"))     # 3.5
print(str(42))          # '42'
print(bool("x"))        # True — non-empty string
print(list("abc"))      # ['a', 'b', 'c'] — iterates the string
Output6 lines
42
1000
3.5
42
True
['a', 'b', 'c']

A failed conversion raises ValueError — int("abc") → ValueError: invalid literal for int() with base 10: 'abc'. (Full error-reading in Part 7.)

Duck typing is the philosophy underneath: Python doesn't ask "what type are you?" so much as "what can you do?". This function accepts anything with a length:

python
def describe_length(thing):
    return "has " + str(len(thing)) + " items"

print(describe_length([1, 2, 3]))    # has 3 items   — a list
print(describe_length("hello"))      # has 5 items   — a string
print(describe_length({"a": 1}))     # has 1 items   — a dict
Output3 lines
has 3 items
has 5 items
has 1 items

No type check, no interface declaration — len() works on all three, so the function works on all three. When you outgrow duck typing, isinstance (6.3) and, later, Protocol (01A.6) give you the checks you need. The LLM SDKs lean on this heavily: anything with the right methods "is" a client.

6.10 Precedence, augmented assignment and the walrus#

Precedence decides 2 + 3 * 4 is 14, not 20 — the familiar arithmetic order, then comparisons, then not, then and, then or. You rarely memorise it; you parenthesise when unsure. ** binds tighter than unary minus on the left (-2**2 == -4, a famous gotcha — parenthesise (-2)**2 if you mean 4).

Augmented assignment x op= y means x = x op y — except for mutables, where it can mean in-place mutation:

python
total = 10
total += 5            # total = total + 5  -> 15 (ints: rebind)
print(total)          # 15

items = [1, 2]
items += [3]          # list.__iadd__ -> IN-PLACE extend, same object!
print(items)          # [1, 2, 3]
Output2 lines
15
[1, 2, 3]

The walrus operator := (Python 3.8+) assigns inside an expression — use it to keep a computed value and test it in one breath:

python
if (n := len("hello")) > 3:
    print("length was", n)     # length was 5
Output1 line
length was 5

Its killer app is "compute once, reuse in the condition": if (match := pattern.search(text)):. It also works in comprehensions and while loops. Don't force it where a plain assignment reads better — if (x := f()): earns its keep only when x is used again inside the block.

6.11 Constants by convention#

Python has no const keyword. The convention: UPPER_CASE names at module level, documented as not-to-be-reassigned:

python
MAX_RETRIES = 3
DEFAULT_TIMEOUT_SECONDS = 30
SUPPORTED_PROVIDERS = ("openai", "anthropic", "gemini", "openrouter")

It costs nothing and signals intent to every reader and linter. If you need enforced immutability, that's Final type hints (01A.10) or frozen dataclasses (01A.6) — later.


Part 7: Reading your first tracebacks#

Errors are not failures of character — they are the interpreter telling you precisely what it expected and what it got. This part teaches the four errors you'll meet in week one, using real output from this lesson's own files.

7.1 The two families of errors#

  • Syntax errors (SyntaxError and subclasses) — the file can't even be parsed. Nothing runs; you get the error before the first line executes. Detected at compile time.
  • Runtime errors (everything else — NameError, TypeError, ValueError, ZeroDivisionError...) — the code parsed fine but failed while running. You get a full traceback: the call stack plus the exception.

The distinction matters for debugging: a syntax error means "fix the form"; a runtime error means "the logic hit a case it can't handle" — often data-dependent.

7.2 IndentationError and TabError#

Covered in 5.2 — the >>> y = 2 → IndentationError: unexpected indent case, and the tabs-vs-spaces TabError. Both are compile-time: no traceback header, just File, the offending line, a caret, and the message. When you see one, look at the previous block — the error is usually reported one line after the real mistake.

7.3 SyntaxError: the parser speaks#

text
# py2_style.py — the Python 2 habit
print "hello world"
Example output · illustrative4 lines
  File "/Users/you/.../py2_style.py", line 2
    print "hello world"
    ^^^^^^^^^^^^^^^^^^^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print(...)?

The anatomy: File gives the absolute path (since Python 3.9) and line number; the source line is echoed; the ^^^ underline marks the offending span; the message names the problem — and often suggests the fix (Did you mean print(...)? since 3.10; Did you mean 'while'? for the typo whille since 3.14 — older versions print a bare invalid syntax). Read the suggestion literally: Python's compiler knows the grammar and frequently knows what you meant.

Common SyntaxErrors and their usual causes:

Message Usually means
invalid syntax The parser got lost and has no better guess: a missing operator or comma between two things, a statement in the wrong place
expected ':' if, for, while, def or class line without its closing colon
invalid syntax. Maybe you meant '==' or ':=' instead of '='? if x = 1: — assignment where a comparison belongs
Missing parentheses in call to 'print' Python 2 tutorial/code
invalid syntax. Did you mean 'X'? A near-miss keyword (whille, retrun) — the suggestion is 3.14+; earlier versions print only invalid syntax. A mistyped name such as flase is different: it parses fine and fails later as a NameError
'(' was never closed (also [ and {) An unclosed bracket — look at the line the caret points to and the lines just after it
unterminated string literal Quote opened and never closed on the same line
expected an indented block after 'if' statement on line N if x: with nothing indented under it (an IndentationError)

7.4 NameError#

python
# name_error.py
ticket_status = "open"
print(ticket_stauts)   # typo!
Example output · illustrative5 lines
Traceback (most recent call last):
  File "/Users/you/.../name_error.py", line 2, in <module>
    print(ticket_stauts)   # typo!
          ^^^^^^^^^^^^^
NameError: name 'ticket_stauts' is not defined. Did you mean: 'ticket_status'?

Runtime error → full traceback. Read it bottom-up: the last line is the exception (NameError + message); the lines above are the call stack, most recent call last. Here the stack is trivial (<module> = top level of the file), and the caret pinpoints the exact name. The Did you mean suggestion (3.10+) compares against names in scope — it's often right.

NameError causes, in order of likelihood: a typo, using a name before assignment, forgetting import, or a name defined inside a function/if block that isn't visible where you use it (scope rules arrive in 01A.3).

7.5 TypeError#

python
# type_error.py
age = input("Age: ")              # input() ALWAYS returns str
print("Next year you'll be", age + 1)
Example output · illustrative5 lines
Traceback (most recent call last):
  File "/Users/you/.../type_error.py", line 2, in <module>
    print("Next year you'll be", age + 1)
                                 ~~~~^~~
TypeError: can only concatenate str (not "int") to str

The ~~~~^~~ fine-print under age + 1 is the fine-grained location (PEP 657, Python 3.11+): it underlines exactly the sub-expression that failed, not just the line. The message tells you the operation (concatenate) and the types involved (str + int).

TypeError means "right idea, wrong kinds of things": adding incompatible types, calling something that isn't callable, subscripting the unsubscriptable, iterating a non-iterable. The fix is almost always a conversion (int(age), 6.9) or a different operation.

7.6 Anatomy of a traceback, line by line#

Example output · illustrative8 lines
Traceback (most recent call last):
  File "/Users/you/.../deep.py", line 12, in <module>
    result = process(tickets)
  File "/Users/you/.../deep.py", line 8, in process
    return classify(t["status"])
  File "/Users/you/.../deep.py", line 3, in classify
    return STATUS_ORDER.index(status)
ValueError: 'pending' is not in list
  • Traceback (most recent call last): — the stack is printed oldest→newest.
  • Each File line: path, line number, and the function name (<module> = top level).
  • The echoed source line is read from the file on disk at the moment the traceback is printed, not stored from when the code was loaded. In a long-running process (a server, a notebook kernel) whose file you have edited since it started, the line numbers can come from the old code while the echoed text comes from the new, so the two look mismatched. Restart the process before trusting such a traceback.
  • The last line: ExceptionType: message. ValueError = "right type, inappropriate value" (int("abc"), list.index(x) missing, float("x")).

The debugging habit: read the last line first (what failed), then walk the stack upwards (who called whom) to find where the bad value entered. In real projects the stack is 10+ frames deep — you'll learn to skim to your own code (01A.8 teaches the full discipline; 03.10 applies it to LLM code).

7.7 Version differences you'll actually see#

Feature Since What you see
Caret ^ under the failing expression 3.10/3.11 ~~~~^~~ fine-grained locations (3.11)
Did you mean ...? suggestions 3.10 NameError, SyntaxError, AttributeError hints
Keyword-typo suggestions (whille → while) 3.14 invalid syntax. Did you mean 'while'? instead of a bare invalid syntax
Coloured tracebacks 3.13 ANSI colours on a TTY; plain when piped; NO_COLOR/PYTHON_COLORS control it
New REPL error display 3.13 Same messages, nicer formatting
Absolute path in File lines 3.9 Your real path, not the relative one you typed

Five real failures, each with the one-line fix:

pycon
>>> x = [1, 2, 3]
>>> x[5]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    x[5]
    ~^^^
IndexError: list index out of range

Lists are 0-indexed and x[5] needs 6 elements. Use len(x) to check bounds — 01A.4.

pycon
>>> d = {"status": "open"}
>>> d["Status"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    d["Status"]
    ~^^^^^^^^^^
KeyError: 'Status'

Dict keys are case-sensitive. d.get("Status") returns None instead of raising — 01A.4.

pycon
>>> "5" + 3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    "5" + 3
    ~~~~^~~
TypeError: can only concatenate str (not "int") to str

Convert first: int("5") + 3 → 8. Strong typing, remember?

pycon
>>> import jsons
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'jsons'

(ModuleNotFoundError is ImportError's precise subclass.) Typo? Not installed? Wrong environment? Check pip list/uv pip list — 01A.7 and 01B.1.

pycon
>>> print("unclosed
Traceback (most recent call last):
  File "<stdin>", line 1
    print("unclosed
          ^
SyntaxError: unterminated string literal (detected at line 1)

Strings can't span lines unless triple-quoted ("""...""") or backslash-continued.


Part 8: Style and tooling in one page#

Deep-dive

8.1 PEP 8, the one-page version#

PEP 8 is the style guide — "readability counts" made concrete. The rules that matter day-to-day:

  • 4 spaces per indent; ≤88 char lines (the formatter's default; PEP 8 says 79, the ecosystem uses 88).
  • snake_case names; PascalCase classes; UPPER_CASE constants.
  • Two blank lines around top-level defs; one inside functions between logical blocks.
  • Imports at the top, grouped: stdlib → third-party → local, alphabetised within groups.
  • One statement per line; spaces around operators (x = 1 + 2, not x=1+2); slices treat : like a binary operator — ham[lower:upper], ham[lower:upper:step] — with spaces on both sides only for complex expressions, e.g. ham[lower + offset : upper + offset].
  • Docstrings on public functions/classes.

You don't memorise it — 8.2 automates it.

8.2 Auto-formatting and linting with ruff#

ruff (current 0.17.x as of November 2026) is the standard Python linter+formatter — absurdly fast, one binary, configured in pyproject.toml. Two commands cover 90% of its value:

bash
uvx ruff format .        # rewrite files to canonical style (like black, but instant)
uvx ruff check .         # lint: unused imports, shadowed builtins, syntax smells
uvx ruff check --fix .   # auto-fix the safe ones

(uvx runs a tool without installing it into your project — 01B.1 sets up the permanent configuration; pipx run ruff or pip install ruff are the alternatives.) Run ruff format on every file you write and ruff check before committing; it enforces the PEP 8 page above and catches real bugs (unused variables, == vs is on literals, mutable default arguments — the last one you'll meet in 01A.3).

8.3 Your editor: VS Code and others#

If you use VS Code (the path's default in 00.1):

  1. Install the Python extension (Microsoft) — it bundles Pylance (intelliSense + type-aware completions).
  2. Select the interpreter: Cmd/Ctrl+Shift+P → "Python: Select Interpreter" → pick your python3 (or the uv-managed one). Wrong interpreter = wrong imports = confusing errors; this is the most common VS Code Python problem.
  3. The extension gives you: syntax highlighting, autocomplete, go-to-definition, a Run Python File button (▶), and an integrated terminal that inherits the selected interpreter.
  4. Indentation: the status bar's indentation indicator (bottom-right, shows Spaces: 4 or Tab Size: 4) toggles between spaces and tabs for the open file — click it and choose Indent Using Spaces. The underlying settings are "editor.insertSpaces": true and "editor.tabSize": 4. Getting this wrong is the #1 cause of TabError (5.2).
  5. Optionally point it at ruff for format-on-save ("editor.formatOnSave": true + "[python]": {"editor.defaultFormatter": "charliermarsh.ruff"}) — details in VS Code's Python docs.

Other editors (JetBrains, Neovim, Sublime) all have first-class Python support; the skills transfer — what matters is an editor that knows Python, not which one.

8.4 The Python cheat sheet#

One page, everything from this lesson:

You want to... You write
Run a file python3 file.py (or uv run file.py)
Run, then keep the REPL python3 -i file.py — script's names stay defined
Run a one-liner python3 -c "print(6*7)"
Run a module python3 -m this
Get a prompt python3 (the REPL)
Make a venv python3 -m venv .venv then source .venv/bin/activate
Check the version python3 --version / python3 -VV
See which binary python3 -c "import sys; print(sys.executable)"
See keywords python3 -c "import keyword; print(keyword.kwlist)"
Print without newline print("x", end="")
Custom separator print("a", "b", sep=" - ") prints a - b
Read a line of input name = input("Name: ") (always str!)
Exit with a code sys.exit(3) or raise SystemExit("msg")
Last REPL result _
Help on a thing help(len) / dir()
Format code uvx ruff format .
Lint code uvx ruff check .
Is it same object? x is y (identity) vs x == y (equality)
Test for nothing x is None — never x == None
Default if empty name or "anonymous"
Assign in a condition (n := len(items)) — walrus, 3.8+

Common misconceptions#

Misconception Reality
"Python is slow because it's interpreted." The interpreter overhead is real but tiny next to I/O and library calls — and the libraries doing the heavy work (NumPy, HTTP clients, model APIs) contain optimised native code. Measure before optimising; 01A.10 covers performance sense.
"x = 5 puts 5 in a box called x." It sticks the name x onto the int object 5. Names point; they don't contain. This is why y = x then x = 20 leaves y at 10.
"is and == are interchangeable." == compares values; is compares identity. int("7001000") is int("7001000") is False while == is True. Use is for None/singletons, == for everything else.
"Variables have types." Values have types. The same name can point at a str today and an int tomorrow — legal, though often unwise.
"Python will convert types for me like JavaScript/PHP." Strong typing: "5" + 3 raises TypeError. Convert explicitly with int(), str(), float().
"0 and "" are falsy, so 0.0, [], {} and () are too — and that's all." Right — and everything else is truthy, including "0", " ", [0] and {"a": 0}. Empty containers and None complete the falsy list.
"input() gives me a number if I type one." It always returns str. int(input(...)) or face the TypeError.
"Indentation is just formatting." It is the syntax. Wrong indentation is a SyntaxError/IndentationError/TabError, and tabs mixed with spaces in a way that makes the structure ambiguous are rejected outright.
"A syntax error means some line ran and broke." Syntax errors are compile-time: the whole file is parsed before anything executes. Nothing ran.
"The REPL is a toy; real work needs files." Both: the REPL is for thinking, files are for keeping. Everything typed at >>> is valid file syntax — promote good experiments into .py files.
"Python 2 code still runs on Python 3." It doesn't — print "x" is a SyntaxError today. Python 2 hit end-of-life on 1 January 2020; any tutorial showing it is obsolete.
"del x deletes the object." It deletes the name x. The object survives if other names still point at it; it dies only when the last reference goes (then the garbage collector reclaims it).
"Any Python 3 is fine." 3.10 went end-of-life in October 2026. Use 3.11+ (3.13+ recommended) — older versions lack the error messages, REPL and libraries this path assumes.
"python, python3 and py are the same thing." They're different launchers that may point at different installs. python3 -c "import sys; print(sys.executable)" tells you the truth.

Key takeaways#

  • Python is interpreted, dynamically typed, strongly typed, garbage-collected and indentation-delimited. "Interpreted" = the python3 program reads and executes your .py files directly (via bytecode); "dynamic" = types live on values, not variables; "strong" = no silent type conversion; "garbage-collected" = memory is reclaimed automatically; "indentation-delimited" = whitespace defines blocks.
  • A program is a .py file run top-to-bottom once. Run it with python3 file.py, a one-liner with python3 -c, a module with python3 -m, or experiment in the REPL (python3 alone). Notebooks (Jupyter) are for exploration, not production code.
  • Install 3.13+ (3.11 minimum). Feature releases come yearly; each is supported ~5 years. 3.10 is end-of-life as of October 2026; Python 2 has been dead since January 2020.
  • uv is the recommended installer/runner: uv python install 3.13, uv run file.py. Alternatives: python.org installers (tick "Add to PATH" on Windows), Homebrew (python3 and python3.x), distro packages (check versions — they lag), or the stdlib python3 -m venv fallback.
  • python vs python3 vs py is historical naming, not different languages. Find your real interpreter with sys.executable.
  • __name__ == "__main__" distinguishes "run directly" from "imported" — the guard that makes a file both script and library.
  • Exit codes (0 success, 1 error, sys.exit(n)) are how scripts signal each other; unhandled exceptions exit 1.
  • The REPL (Read-Eval-Print Loop) evaluates expressions interactively: _ is the last result, help()/dir() inspect, exit() or Ctrl-D leaves. On 3.13+ it's multiline, coloured and has history; exit/quit/help also work as bare commands on a real terminal (exit() is the portable form); PYTHONSTARTUP runs a file at launch; python3 -i file.py runs a script then opens the REPL with its names still defined.
  • Syntax in one breath: statements do things, expressions produce values; blocks are 4-space indents (never mixed tabs/spaces); # comments, """docstrings""", snake_case/PascalCase/UPPER_CASE names, ~35 keyword.kwlist reserved words, never shadow builtins.
  • Names point at objects — they aren't boxes. = binds a name; y = x aliases; mutating a shared list affects every alias; del removes names, not objects.
  • is is identity, == is equality — is for None/singletons only. Truthiness: 0, 0.0, "", empty containers and None are falsy; everything else (including "0" and [0]) is truthy.
  • Operators: / floats, // floors, % remainder (sign of divisor), ** power, chained comparisons, in/not in, and/or return operands (short-circuit), := assigns inside expressions.
  • Read tracebacks bottom-up: last line = exception type + message; above = call stack; caret = exact failing expression (3.11+). Syntax errors are compile-time (nothing ran); runtime errors give the full stack.
  • Style: PEP 8 in one page, uvx ruff format + uvx ruff check automate it, VS Code's Python extension + interpreter selection, and the cheat sheet in 8.4 is your pocket reference.

Where you'll use this in the AI path#

Skill from this lesson Where it shows up next
Running scripts, __main__, exit codes Every later lesson's samples; project layout in 01B.1
The REPL for quick experiments Probing provider APIs by hand in 03.1 §1.4 before SDK code
Dicts/lists-of-dicts as data shapes The message format itself in 03.2 and JSON schemas in 03.4
Reading tracebacks and exception types The LLM error taxonomy in 03.8 §3.1 and debugging methodology in 03.10
f-strings and string building Prompt templates in 04.10 §2.2 — f-strings themselves are 01A.2
is/==, truthiness, None checks Everywhere: if response is None, finish_reason == "stop", optional fields — the idiom of every SDK sample
Variables, functions, control flow 01A.3; data structures in 01A.4; errors properly in 01A.8; files/JSON/CSV in 01A.9; typing in 01A.10

Terms introduced in this lesson#

Term One-line definition
Interpreter The program that reads and executes Python source (CPython compiles to bytecode, then runs it)
Bytecode The compact intermediate instructions the interpreter executes
Program / script A .py file of instructions run top-to-bottom once
REPL Read-Eval-Print Loop: the interactive >>> interpreter
Prompt (>>>, ...) The REPL's input marker; ... means "inside a block"
-c / -m / -i Run code from the command line / run a module / enter REPL after
Module A .py file of reusable code (preview; 01A.7)
Notebook (Jupyter .ipynb) A document of executable cells mixing code and prose
IPython A richer third-party REPL
sys module Built-in module exposing interpreter state (sys.executable, sys.argv, sys.exit)
sys.executable The exact interpreter binary running your code
sys.argv Command-line arguments; argv[0] is the script name
__name__ / __main__ '__main__' when run directly, module name when imported
__main__ guard if __name__ == "__main__": — run-as-script vs importable-library switch
Exit code Integer returned to the shell: 0 success, non-zero failure
sys.exit() / SystemExit End the program with a chosen exit code
PYTHONSTARTUP Env var naming a .py file executed at interactive startup
Expression Code that produces a value (2 + 3, len(x))
Statement Code that does something (x = 1, print(x), if ...:)
Indentation Leading whitespace defining blocks; 4 spaces per level
IndentationError / TabError Compile-time errors for bad/mixed indentation
Comment # to end-of-line note for humans
Docstring """...""" first-statement string documenting a module/function/class
Identifier A name for a variable, function, class or module
Keyword One of ~35 reserved words (keyword.kwlist)
Soft keyword Reserved only in context (match, case, type, _, lazy — keyword.softkwlist)
Builtin Names available without import (print, len, str...)
Shadowing Rebinding a builtin name — legal, usually a bug
snake_case / PascalCase / UPPER_CASE Naming conventions for vars/functions / classes / constants
Constant (convention) UPPER_CASE name intended never to be reassigned
Name binding = attaches a name to an object; it does not copy or box
Object The thing a name points at; has a type and an identity (id())
Rebinding Pointing a name at a different object
Aliasing Two names pointing at the same object
Chained assignment a = b = value — one object, two names
Unpacking / multiple assignment first, second = "ab" — distribute values across names
del Remove a name binding
Dynamic typing Types belong to values; names have none
Strong typing No implicit type conversion; explicit int()/str()/float()
type() / isinstance() Get a value's class / test membership in a class
int / float / bool / str / None The five core types (arbitrary-precision int, IEEE-754 float, int-subclass bool, immutable str, NoneType singleton)
Arbitrary precision Python ints never overflow
Mutable / immutable Can / cannot change in place (list,dict,set vs int,str,tuple)
Hashable Usable as dict key/set member (immutables generally are)
Truthiness / falsy Every value's boolean reading; falsy = 0,0.0,"",empty containers,None,False
== vs is Value equality vs object identity
Singleton A unique object (None, True, False) compared with is
Operator Symbol for an operation (+, ==, in, and, :=...)
Short-circuit and/or return an operand and may skip evaluating the right side
Augmented assignment x += y — rebind for immutables, mutate for mutables
Walrus operator := Assign inside an expression (3.8+)
Operator precedence Which operation binds first (** > *// > +/- > comparisons > not > and > or)
Type conversion Explicit int(x), str(x), float(x), bool(x), list(x)...
Duck typing "If it has the methods, it works" — no declared type needed
SyntaxError Parse-time failure; nothing ran
IndentationError / TabError Subclasses for indentation mistakes
Runtime error / exception Failure while executing (NameError, TypeError, ValueError...)
Traceback The printed call stack + exception for a runtime error
Call stack The chain of active function calls, printed most-recent-last
NameError Name used before binding / typo / missing import
TypeError Operation applied to wrong kinds of values
ValueError Right type, inappropriate value
SyntaxWarning Compile-time warning (e.g. is with a literal)
Fine-grained location Caret under the exact failing sub-expression (3.11+, PEP 657)
repr() String giving an unambiguous representation of a value
PEP 8 The Python style guide
ruff Fast linter+formatter (ruff format, ruff check)
uv / uvx Python/package manager and tool runner
Virtual environment Isolated package environment (preview; 01A.7, 01B.1)

All terms are also collected in the glossary.


Exercises#

Work through these in order — they use only the standard library and the files from this lesson. Solutions for all items are in the single collapsible block at the end of this section.

  1. REPL arithmetic (4.2): In the REPL, compute (17 * 23) + 5, then multiply the result by 2 without retyping it (hint: _).

  2. First file (2.5, 3.1): Write ticket_count.py that defines a list of 4 ticket dicts (invent subjects/statuses) and prints how many are "open". Run it with python3 ticket_count.py.

  3. Arguments (3.7): Write greet.py so python3 greet.py Ada Grace prints Hello, Ada Grace! and plain python3 greet.py prints Hello, world! — use sys.argv[1:] and " ".join(...).

  4. The __main__ guard (3.4): Given a file tool.py containing def main(): print("ran") and the __main__ guard, predict what prints for python3 tool.py vs import tool in the REPL — then verify.

  5. Aliasing (6.2): Predict, then verify:

    python
    a = b = [1, 2]
    a.append(3)
    print(a, b, a is b)

    Now fix it so b stays [1, 2] — without changing what a becomes.

  6. is vs == (6.7): A colleague wrote if status is "open":. Explain why it sometimes works and why it's still wrong, then write the correct check. Verify with s1 = "open" and s2 = "".join(["op", "en"]) — and try s3 = "op" + "en" too; notice which construction CPython folds into a single constant.

  7. Truthiness (6.6): Which of these are falsy: 0, "0", [], {}, (), None, False, [0], " ", 0.0? Verify each with bool().

  8. Operators (6.8): Compute by hand, then verify: -7 // 3, -7 % 3, 2 ** 10, "ell" in "hello", 0 or "fallback", 5 and 10.

  9. Conversion (6.9): What does each print: int(" 42 "), int("1_000"), float("2.5") + 0.5, str(3.0), list("abc"), bool([0])? Which one raises?

  10. print (5.7): Use sep and end to print the three columns name, status, priority separated by | with no trailing newline, then print done on the same line.

  11. input (5.7): Write a two-question script (name, age) that prints "<name> will be <age+1> next year". Pipe answers with printf 'Ada\n30\n' | python3 script.py.

  12. Fix the traceback (7.4–7.5): type_error.py crashes with TypeError when you type 30. Fix it so it prints Next year you'll be 31 — and explain why the original failed.

  13. Keywords (5.5): Try class = 5 in the REPL and read the SyntaxError. Then use keyword.kwlist to find a keyword you didn't know was reserved.

  14. Indentation (5.2): mixed_indent.py raises TabError. Reproduce the error, then fix the file (convert the tab to 4 spaces) and confirm greet("Ada") prints both lines.

  15. Which Python (2.6): Run python3 -c "import sys; print(sys.executable, sys.version.split()[0])" and confirm you're on 3.11+. Then find where python3 lives (which python3 on POSIX, Get-Command python on Windows).

Solutions
  1. pycon
    >>> (17 * 23) + 5
    396
    >>> _ * 2
    792
  2. python
    # ticket_count.py
    tickets = [
        {"id": 1, "subject": "login broken", "status": "open"},
        {"id": 2, "subject": "slow export", "status": "closed"},
        {"id": 3, "subject": "billing question", "status": "open"},
        {"id": 4, "subject": "dark mode", "status": "open"},
    ]
    print(sum(1 for t in tickets if t["status"] == "open"), "open of", len(tickets))

    Output: 3 open of 4

  3. python
    # greet.py
    import sys
    name = " ".join(sys.argv[1:]) or "world"
    print("Hello,", name + "!")
    console
    $ python3 greet.py Ada Grace
    Hello, Ada Grace!
  4. python3 tool.py prints ran. import tool in the REPL prints nothing — the guard stops main() from running on import. (Verified with showname.py in 3.4: __name__ is '__main__' when run directly and 'tool' when imported.)

  5. Output · before the fix: [1, 2, 3] [1, 2, 3] True. Fix — give b its own list4 lines
    a = [1, 2]
    b = list(a)        # or a.copy() — a NEW list with the same items
    a.append(3)
    print(a, b)        # [1, 2, 3] [1, 2]
  6. is compares identity, not value. "open" is "open" appears to work because identical literals may share one interned object — but that's compiler luck, not a rule. The trap: s3 = "op" + "en" is constant-folded at compile time, so s3 really is the same object as the "open" literal — s3 is "open" prints True (with a SyntaxWarning: "is" with 'str' literal). Build the string at run time instead — s2 = "".join(["op", "en"]) — and s2 is "open" is False while s2 == "open" is True. That's the real lesson: is on values can appear to work or fail depending on compiler optimisations, which is exactly why it's meaningless for them. Correct check: if status == "open":. Reserve is for None/True/False.

  7. Falsy: 0, [], {}, (), None, False, 0.0. Truthy (the traps): "0", [0], " ". Verified against the falsy/truthy table in 6.6.

  8. -7 // 3 → -3; -7 % 3 → 2; 2 ** 10 → 1024; "ell" in "hello" → True; 0 or "fallback" → 'fallback'; 5 and 10 → 10. (Floor division rounds toward −∞, so the remainder takes the divisor's sign.)

  9. 42, 1000, 3.0, '3.0' (a string!), ['a', 'b', 'c'], True. None raise — int(" 42 ") strips whitespace and int("1_000") accepts underscores. (int("abc") would raise ValueError.)

  10. python
    print("name", "status", "priority", sep=" | ", end="")
    print("done")

    Output: name | status | prioritydone — end="" really does glue the next print onto the same line with nothing in between. Make end the separator too: print("name", "status", "priority", sep=" | ", end=" | ") followed by print("done") gives name | status | priority | done. (An f-string, from 01A.2, is the other way to build such a line.)

  11. python
    # next_year.py
    name = input("Name: ")
    age = int(input("Age: "))
    print(name, "will be", age + 1, "next year")
    console
    $ printf 'Ada\n30\n' | python3 next_year.py
    Name: Age: Ada will be 31 next year
  12. The original failed because input() returns str, and str + int is a TypeError. Fix:

    python
    age = int(input("Age: "))
    print("Next year you'll be", age + 1)

    Output with 30 piped in: Age: Next year you'll be 31 (prompt and output share a line because input's prompt has no newline).

  13. class = 5 → SyntaxError: invalid syntax with the caret under class. keyword.kwlist on 3.14 lists 35 keywords; keyword.softkwlist lists ['_', 'case', 'match', 'type'] — soft keywords are only reserved in context (match/case in patterns, type in type X = ..., _ as the wildcard, lazy from 3.15).

  14. Run python3 mixed_indent.py → TabError: inconsistent use of tabs and spaces in indentation at line 4. Replace the literal tab with 4 spaces, then python3 -c "from mixed_indent import greet; greet('Ada')" prints hi Ada then done. (The file itself only defines greet — running python3 mixed_indent.py directly prints nothing, which is exactly what the __main__ guard in 3.4 is for.)

  15. Example: /opt/homebrew/opt/python@3.14/bin/python3.14 3.14.6. which python3 → the same path (or a symlink to it). If the version is < 3.11, install 3.13 with uv python install 3.13.


Check yourself#

  1. Name the five adjectives that describe Python, and what each one means in practice.

  2. What's the difference between running python3 file.py, python3 -c "...", python3 -m mod, and bare python3?

  3. Why does this path recommend uv, and what does uv python install actually install?

  4. python vs python3 vs py — which should you type on macOS, on Windows, and why does it matter which one you pick?

  5. What does if __name__ == "__main__": prevent, and when does __name__ equal '__main__'?

  6. A script prints a traceback and the shell shows exit code 1. What happened, and how could the script have exited 0 instead?

  7. In the REPL, what do _, help(), dir(), ..., and exit() each do?

  8. Why is x = 5 silent in the REPL but x + 5 prints 10?

  9. a = b = [1, 2]; a.append(3) — what are a and b now, and why? How do you give b its own copy?

  10. Evaluate: isinstance(True, int), "0" or "x", -7 % 3, 1 < 2 <= 3, bool([0]), bool("").

  11. When is is the right operator, and when must you use ==? Give the one rule that never fails.

  12. input("Age: ") returns "30". What happens at age + 1, what error, and what's the fix?

  13. Read this traceback bottom-up: what's the exception, what line failed, and what does the stack tell you?

    Traceback (most recent call last):
      File "/Users/you/.../report.py", line 9, in <module>
        print(classify(t["status"]))
      File "/Users/you/.../report.py", line 4, in classify
        return LABELS[status]
    KeyError: 'pending'
  14. List the falsy values. Is [0] falsy? Is "0"?

  15. What do uvx ruff format and uvx ruff check do, and why run them on every file?


Further resources#


← Module 00: Developer Foundations | Module 01A overview | 01A.2 — Numbers, Strings and Text →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close