01 / 22 · Getting Started
Running Python
What a program and an interpreter are, installing Python 3.14, four ways to run code (the interactive prompt, a script, python -m, a notebook), what happens between a file and its output, reading a traceback, and the plan of the course.
On this page 10
This course starts from nothing. It assumes that you can open a terminal and type a command, and nothing about programming. It ends with the tools that the machine-learning courses of this site use every day: NumPy arrays, pandas tables and Matplotlib figures. On the way it explains what Python does with each line you write, down to the objects in memory and the instructions the interpreter executes, because that model is what lets you predict what a program will do instead of guessing. This first note gets Python onto your machine, runs code in each of the four ways people run it, follows one small file from text to output, and shows how to read the error report that Python prints when something goes wrong.
Conventions. Everything in the course runs on CPython 3.14.7, the reference implementation of Python, on an Apple M1 under macOS. Lines that start with the terminal’s prompt $ are typed into a terminal; the prompt itself is not part of the command. Lines that start with >>> or ... are typed into Python’s interactive prompt, and the lines without a prompt under them are what Python printed. Long error reports are trimmed to their last lines, with the cut marked ....
What a program and an interpreter are#
A program is a list of instructions for a computer, written down as text. The text is called source code, and a file of Python source code ends in .py. The processor of a computer cannot read that text. It executes machine code: numbered instructions such as “add two registers” or “jump to this address”, different for each kind of processor. Something has to stand between the text and the processor.
For Python that something is the interpreter, itself a program, usually called python. It reads your source code and carries out what it says. The standard interpreter, CPython, is written in C and is the one you download from python.org. Other implementations exist (PyPy, for instance, runs the same language with a different engine), but when people say “Python” they nearly always mean CPython, and so does this course.
A language version is a promise about what source code means. Python 3.14 was released in October 2025; it is the version this course uses, and every example was run on 3.14.7. Python 3.15 followed in October 2026, and the notes say where it changes something they show. A program written for 3.14 runs on 3.15 with rare exceptions, but not the other way round: a newer version adds features that an older interpreter does not understand.
Installing Python 3.14#
There are two common ways, and either is fine for the whole course.
- The official installer. Download it from python.org/downloads. On macOS this is a
.pkginstaller that adds the commandspython3andpython3.14. On Windows the recommended route since 3.14 is the Python install manager, from the same page or the Microsoft Store;py install 3.14installs that version, and the older full installer is deprecated (Python documentation, Using Python on Windows). On Linux, the distribution’s package manager usually has a recent version. - uv. uv is a fast tool that installs Python versions and manages the packages of a project. After installing uv itself,
uv python install 3.14downloads CPython 3.14 and, with recent versions of uv, adds apython3.14command to~/.local/bin. Inside a project folder,uv run pythonruns the project’s interpreter with the project’s packages. The modules and environments note explains environments properly.
Check what you have:
$ python3.14 --version
Python 3.14.7
The command name varies: python3 on macOS and most Linux systems, python or py on Windows, python inside an activated environment. This course writes python.
Baseline: the interactive prompt#
The simplest way to run Python is to type python with nothing after it. The interpreter starts the REPL, for read–evaluate–print loop: it reads one statement, evaluates it, prints the result if there is one, and waits for the next.
$ python3.14
Python 3.14.7 (main, Sep 1 2026, 14:05:28) [Clang 22.1.3 ] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 2 + 3
5
>>> x = 7
>>> x * 6
42
>>> print("hello")
hello
Read it line by line. 2 + 3 is an expression, a piece of code that has a value, and the REPL prints the value, 5. x = 7 is an assignment: it gives the name x to the value 7 and has no value of its own, so nothing is printed. x * 6 uses the name, and the REPL prints 42. print("hello") is a call of the function print, which writes its argument to the terminal; the REPL itself prints nothing more, because print returns no value worth showing. exit or Ctrl-D leaves the REPL.
The REPL is the fastest way to try one idea. Since 3.13 it is a new implementation with multi-line editing, colour and a history of whole statements; 3.14 adds syntax highlighting and completes module names after import when you press Tab (What’s New in Python 3.14). Where it fails is everything beyond one idea: when the REPL exits, every name and value is gone, and the statements you typed are not a program anyone can run again.
A script: python file.py#
A script is a source file that the interpreter runs from top to bottom. Save these three lines as area.py:
width = 3
height = 4
print(width * height)
and run it:
$ python area.py
12
The rules differ from the REPL in two ways. Statements run in order from the first line to the last, and then the program ends. And a script prints only what it asks to print: a bare expression such as width * height on a line of its own is computed and thrown away, because there is no REPL to show it. Anything after the file name becomes the list sys.argv, so a script can be told what to work on:
$ cat args.py
import sys; print(sys.argv)
$ python args.py data.csv 10
['args.py', 'data.csv', '10']
The arguments arrive as text, '10' and not the number 10; the next note shows why that difference matters.
A module: python -m#
python -m name finds the module called name on Python’s search path and runs it as the main program. Many tools that ship with Python are run this way, which guarantees that the tool belongs to the same interpreter as the python you typed:
| Command | What it does |
|---|---|
python -m venv .venv | create a virtual environment in the folder .venv |
python -m pip install numpy | install a package into this interpreter |
python -m timeit "expression" | time a small piece of code |
python -m json | pretty-print JSON read from standard input (new as a command in 3.14) |
python -m pytest | run the tests of a project (after installing pytest) |
$ python -m timeit '"-".join(str(n) for n in range(100))'
50000 loops, best of 5: 6.08 usec per loop
The timing is one run on the setup above and will differ on other machines. The difference between python file.py and python -m name is how the file is found: by its path in the first case, by the module search that import uses in the second. The modules note explains that search.
Notebooks#
A notebook (Jupyter, or Google Colab, which runs Jupyter notebooks in a browser) is a document of cells. A code cell is sent to a running interpreter, called the kernel, and its output, including tables and figures, is saved in the document under the cell. Markdown cells hold text. With uv, uv run --with jupyter jupyter lab starts JupyterLab from a project folder (uv documentation).
Notebooks combine the REPL’s immediacy with a record of what was run, which is why data analysis and teaching use them. The NLP and Generative Models courses on this site come with notebooks. They have one trap that scripts do not: the kernel keeps every name from every cell you ran, in the order you ran them, which need not be the order on the page. A cell that uses a name defined in a cell further down, or one that you since deleted, works now and fails for the next reader. The execution counter next to each cell, [3], records the order. Before sharing a notebook, restart the kernel and run all cells from the top; if it still works, its saved outputs are what the code produces.
What happens when you run a file#
What happens when you run python area.py
- The source is a text file. Nothing has run yet.
- The compiler reads the whole file. It cuts the text into tokens (names, numbers, operators), checks that they form valid Python and builds a syntax tree, then translates the tree into bytecode.
- The result is a code object. The module
disprints its instructions; for line 3 ofarea.pyit lists nine, and the figure shows the first six in the orderdislists them (the remaining three discard the result ofprintand end the module).LOAD_NAME widthpushes the value namedwidthonto a stack of values,BINARY_OP *replaces the top two values by their product, andCALL 1callsprintwith one argument. - The interpreter loop fetches each instruction and runs the C code that implements it.
printwrites 12 to the terminal. The last instruction returns, and the program ends.
For a file you import rather than run, CPython saves the compiled code object to a .pyc file in a __pycache__ folder next to it, named after the interpreter (__pycache__/area.cpython-314.pyc), and the next import skips the compiler if the source has not changed. The main script is compiled again on every run.
Two consequences follow, and both are visible in everyday use. A file with a syntax error on its last line prints nothing at all, not even the output of its first line: the compiler stops before anything runs. And code that is wrong in a way the compiler cannot see, such as a division by a number that turns out to be zero, runs until the moment that instruction executes. The How CPython runs code note opens the interpreter loop and the value stack properly, and the ACOS course follows the same path down to the operating system.
Errors and how to read a traceback#
When a statement fails, Python raises an exception. If nothing in the program handles it (the files and exceptions note shows how to), the interpreter prints a traceback and exits with a nonzero status. Take a script that averages two weeks of numbers, one of which is empty:
def average(values):
return sum(values) / len(values)
def report(name, values):
print(name, average(values))
report("week 1", [12, 15, 9])
report("week 2", [])
$ python prices.py
week 1 12.0
Traceback (most recent call last):
File ".../prices.py", line 8, in <module>
report("week 2", [])
~~~~~~^^^^^^^^^^^^^^
File ".../prices.py", line 5, in report
print(name, average(values))
~~~~~~~^^^^^^^^
File ".../prices.py", line 2, in average
return sum(values) / len(values)
~~~~~~~~~~~~^~~~~~~~~~~~~
ZeroDivisionError: division by zero
(The folder part of each path is shortened to ....) The rule for reading it:
- Start at the last line. It names the exception type,
ZeroDivisionError, and a message,division by zero. That is what went wrong. - The line above it is where. Each
Fileentry is one active function call, a frame, with its file, its line number and the function’s name. The list runs from the oldest call at the top to the most recent at the bottom: “most recent call last”. The bottom frame, line 2 insideaverage, is where the exception was raised. - The marks under the source line point into it. Since Python 3.11 (PEP 657) the traceback underlines the expression that failed:
^marks the part that raised (here the/),~the rest of the expression around it. - Walk up to find the cause. The failing line is often correct; the bad value came from higher up. Here
averagedivided correctly, and the empty list came from line 8.
The first line of output, week 1 12.0, also matters: the first call ran to completion before the second failed. Statements run in order until one raises.
A syntax error looks different, because it is found by the compiler, before anything runs. There are no frames, only the place in the file:
$ python late.py
File ".../late.py", line 2
whille True:
^^^^^^
SyntaxError: invalid syntax. Did you mean 'while'?
The file’s first line was print("start"), and start was never printed. The suggestion “Did you mean ‘while’?” is new in 3.14; earlier versions say only invalid syntax. Error messages have improved in every release since 3.10, and they are worth reading slowly. Two more that a beginner meets in the first hour:
$ python name.py
Traceback (most recent call last):
File ".../name.py", line 2, in <module>
print(totl)
^^^^
NameError: name 'totl' is not defined. Did you mean: 'total'?
$ python paren.py
File ".../paren.py", line 1
print("hello"
^
SyntaxError: '(' was never closed
The machine-learning courses meet tracebacks constantly, and most of them are long because the failing line sits deep inside a library such as NumPy or PyTorch. The rule is the same: read the last line, then find the lowest frame that is in your own file. That frame is usually where the wrong value or shape was passed in.
The plan of the course#
The course has six sections. Each note follows the same pattern: a rule stated exactly, a small example with its real output, the model underneath that explains the rule, and the mistake that the rule predicts.
- Getting Started. Running code (this note); values, types and names, where the central idea of the course appears: a name refers to an object, and assignment copies nothing; control flow, from
iftomatch; functions, with their arguments, scopes and call stack; and strings and text as Unicode. - Data Structures. Lists and tuples and dictionaries and sets, with what each operation costs and why; iteration, comprehensions and generators, the protocol behind every
forloop; and files and exceptions. - Abstraction. Classes, the data model that lets your objects work with
len,+andfor, closures and decorators, modules, packages and environments, and type hints. - Reliable Code. Testing with pytest, and debugging and profiling.
- Under the Hood. How CPython runs code: bytecode, reference counting and the garbage collector; writing fast Python; and concurrency with threads, processes and asyncio, with and without the global interpreter lock.
- Scientific Python. NumPy arrays, data frames with pandas and plotting with Matplotlib.
What the other courses need. The Machine Learning course ends every note with a runnable script built on functions, lists and dictionaries, comprehensions and NumPy: the first three sections and the NumPy note. PyTorch in the Deep Learning course defines a network as a class whose instances are called like functions, which is the data model of section 3. The NLP course starts from text as data, Unicode strings and dictionaries of counts, which are sections 1 and 2. Sections 4 and 5 are for writing code that others can rely on and that runs fast enough; the machine-learning courses do not assume them.
What changed#
| REPL | Script | python -m | Notebook | |
|---|---|---|---|---|
| Start it with | python | python file.py | python -m name | JupyterLab, Colab |
| Unit of input | one statement | the whole file | a module found by name | one cell |
| Prints values of bare expressions | yes | no | no | the last expression of a cell |
| State after it ends | lost | lost | lost | kept in the kernel until restart |
| Good for | trying one idea | programs to run again | tools that ship with Python | exploration with tables and figures |
Limitations#
- One implementation. The bytecode, the
.pycnaming and the exact wording of error messages are CPython’s and change between versions; the language rules in the rest of the course do not depend on them. - One machine. The timing above is from one run on one machine and only illustrates what
timeitprints. The debugging and profiling note shows how to measure properly. - Environments are postponed. Installing packages into the right place, and keeping a project’s versions fixed, is the subject of the modules and environments note. Until then, everything in the course needs only the standard library.
What you should remember#
- The interpreter is a program that reads your source code and carries it out. The standard one is CPython; this course uses 3.14.
- The REPL runs one statement at a time and prints the value of each expression. A script runs a whole file from top to bottom and prints only what it asks to.
python -mruns a module found by name. A notebook keeps the interpreter’s state between cells, in the order you ran them. - CPython compiles the whole file to bytecode first, then executes the bytecode in a loop. Syntax errors stop everything before the first line runs; other errors happen when their line executes.
- Read a traceback from the bottom: the exception and its message, then the most recent frame, then up through the callers to find where the bad value came from.
Code#
The script follows the three-line program of this note through each stage: it compiles the source text into a code object, lists its bytecode, executes it, shows where an imported module’s bytecode would be cached, and catches a syntax error and a runtime error to show what each looks like. It needs only the standard library; run it with python -I stages.py. The bytecode names are those of CPython 3.14 and differ in other versions.
"""Follow one small program through the stages of running it (Python 3.14)."""
import dis
import importlib.util
import sys
import traceback
source = "width = 3\nheight = 4\nprint(width * height)\n"
# 1. Which interpreter runs this file
print(sys.version_info[:3], sys.implementation.name, sys.implementation.cache_tag)
# 2. Compile: source text -> a code object that holds bytecode
code = compile(source, "area.py", "exec")
print(type(code).__name__, code.co_names)
print([ins.opname for ins in dis.get_instructions(code)])
# 3. Execute the code object; its names land in a fresh namespace
namespace = {}
exec(code, namespace)
print(namespace["width"], namespace["height"])
# 4. Where the bytecode of an imported module area.py would be cached
print(importlib.util.cache_from_source("area.py"))
# 5. A syntax error is found while compiling, before anything runs
try:
compile("whille True:\n pass\n", "typo.py", "exec")
except SyntaxError as err:
print(f"{err.filename}, line {err.lineno}: {err.msg}")
# 6. A runtime error: the traceback lists the frames, most recent call last
def average(values):
return sum(values) / len(values)
def report(values):
return f"mean {average(values)}"
try:
report([])
except ZeroDivisionError:
tb = traceback.extract_tb(sys.exc_info()[2])
print([frame.name for frame in tb])
print(traceback.format_exc().splitlines()[-1])
# Output with CPython 3.14.7 on macOS (arm64); the first line shows your version:
# (3, 14, 7) cpython cpython-314
# code ('width', 'height', 'print')
# ['RESUME', 'LOAD_SMALL_INT', 'STORE_NAME', 'LOAD_SMALL_INT', 'STORE_NAME', 'LOAD_NAME', 'PUSH_NULL', 'LOAD_NAME', 'LOAD_NAME', 'BINARY_OP', 'CALL', 'POP_TOP', 'LOAD_CONST', 'RETURN_VALUE']
# 12
# 3 4
# __pycache__/area.cpython-314.pyc
# typo.py, line 1: invalid syntax
# ['<module>', 'report', 'average']
# ZeroDivisionError: division by zero
The output line 12 comes from the print inside the executed program, between the bytecode and the namespace. err.msg is invalid syntax without the “Did you mean” suggestion: the suggestion is added when the traceback is displayed, not stored in the exception.
Next#
Every line of this note’s programs did one of two things: it created a value, such as 3 or [12, 15, 9], or gave a value a name, such as width. The next note asks what exactly a value and a name are. The answer, that a name is a reference to an object and that assignment never copies, explains most of the surprises a newcomer to Python meets.
References#
- Python documentation (3.14): The Python Tutorial, §2 (using the interpreter) and §3 (an informal introduction); Command line and environment (
-m,-c,-I); Using Python on Windows (the Python install manager);dis;traceback;py_compileand PEP 3147 — PYC Repository Directories (the__pycache__folder). - What’s New in Python 3.13 (the new interactive interpreter) and What’s New in Python 3.14 (syntax highlighting in the REPL, import completion, improved error messages,
python -m json). - P. Galindo Salgado, B. Taskaya, A. Askar. PEP 657 — Include Fine Grained Error Locations in Tracebacks. 2021.
- Astral. uv documentation: installing Python, and using uv with Jupyter.
- Project Jupyter. JupyterLab documentation.
- A. Shaw. CPython Internals: Your Guide to the Python 3 Interpreter. Real Python, 2021. Ch. on the compiler and the evaluation loop.
- L. Ramalho. Fluent Python, 2nd ed. O’Reilly, 2022.