Running Python
Program and interpreter, installing Python 3.14, four ways to run code (REPL, script, python -m, notebook), a file's path from text through bytecode to output, reading a traceback, and the plan of the course.
The question of the course
One question drives this course: what actually happens when Python runs your code, and how do you use that to write programs that are correct, clear and fast enough for machine learning? The course assumes only that you can open a terminal and type a command. It ends with NumPy arrays, pandas tables and Matplotlib figures, the tools that the machine-learning courses use every day.
The answer starts with two words. A program is a list of instructions for a computer, written as text. That text is source code, and a file of Python source code ends in .py.
The processor 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 one, but "Python" nearly always means CPython, and so does this course.
This topic gets Python onto your machine, runs code in the four ways people run it, follows one small file from text to output and shows how to read the report Python prints when something goes wrong.
Installing Python 3.14
A language version is a promise about what source code means. This course uses Python 3.14, released in October 2025; every example was run on CPython 3.14.7. A newer version adds features. So code written for 3.14 runs on 3.15 with rare exceptions, but code that uses something new in 3.15 fails on 3.14.
There are two common ways to install it, and either is fine for the whole course.
- The official installer from python.org/downloads. On macOS it adds the commands
python3andpython3.14. On Windows the recommended route since 3.14 is the Python install manager:py install 3.14. On Linux the distribution's package manager usually has a recent version. - uv, a fast tool that installs Python versions and manages the packages of a project.
uv python install 3.14downloads CPython 3.14, anduv run --python 3.14 python file.pyruns a file with it. The topic Modules, packages and environments explains projects and environments properly.
Check what you have:
$ python3.14 --version
Python 3.14.7A line that starts with $ is typed into a terminal. The $ is the terminal's prompt, not part of the command.
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; type whatever name works on your machine.
The interactive prompt
The simplest way to run Python is to type python with nothing after it. The interpreter starts the REPL, the read–evaluate–print loop. It reads one statement, evaluates it, prints the result if there is one, and waits for the next.
$ python
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")
helloYou type after >>>; the lines without a prompt are what Python printed. Read the session line by line.
2 + 3is an expression, a piece of code that has a value. The REPL prints the value,5.x = 7is an assignment. It gives the namexto the value 7 and has no value of its own, so nothing is printed.x * 6uses the name, and the REPL prints42.print("hello")calls the functionprint, which writes its argument to the terminal. The call returns nothing worth showing, so the REPL adds nothing.
exit or Ctrl-D leaves the REPL. Since 3.13 it edits multi-line statements and uses colour, and 3.14 adds syntax highlighting and completes module names after import when you press Tab.
The REPL is the fastest way to try one idea. Its limit is everything beyond one idea: when it exits, every name and value is gone, and what you typed is not a program that 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 samples.py:
batch_size = 32
steps = 4
print(batch_size * steps)and run it:
$ python samples.py
128Two rules differ from the REPL. 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 batch_size * steps on a line of its own is computed and thrown away, because there is no REPL to show it.
Anything after the file name arrives in the list sys.argv, so a script can be told what to work on. Here is args.py:
import sys
print(sys.argv)$ python args.py data.csv 10
['args.py', 'data.csv', '10']The first element is the script's own name. The arguments arrive as text: '10' in quotes, not the number 10. The next topic shows why that difference matters.
python -m and notebooks
python -m name finds the module called name by the same search that import uses and runs it as the main program. Many tools that ship with Python run this way, and -m guarantees that the tool belongs to the same interpreter as the python you typed.
| Command | What it does |
|---|---|
python -m venv .venv |
creates a virtual environment in the folder .venv |
python -m pip install numpy |
installs a package into this interpreter |
python -m timeit "..." |
times a small piece of code |
python -m json |
pretty-prints JSON from standard input (new as a command in 3.14) |
python -m dis samples.py |
lists the bytecode of a file (next block) |
$ python -m timeit '"-".join(str(n) for n in range(100))'
50000 loops, best of 5: 6.39 usec per loopThat timing is one run on one machine; yours will differ.
A notebook (JupyterLab, or Google Colab in a browser) is a document of cells. A code cell is sent to a running interpreter, the kernel, and its output, tables and figures included, is saved under the cell. With uv, uv run --with jupyter jupyter lab starts JupyterLab. Notebooks pair the REPL's immediacy with a record of what ran, which is why data analysis lives in them.
They have one trap that scripts do not. The kernel keeps every name from every cell you ran, in the order you ran them, and that need not be the order on the page. A cell that relies on a cell further down, or on one you have since deleted, works for you and fails for the next reader. The counter next to each cell, such as [3], records the order. Before sharing a notebook, restart the kernel and run all cells from the top.
From text to output
CPython never runs your text directly. It works in two stages.
- The compiler reads the whole file. It cuts the text into tokens (names, numbers, operators), checks that they form valid Python, arranges them into a syntax tree and translates the tree into bytecode: simple instructions for a virtual machine, kept in a code object.
- The interpreter loop, written in C, fetches the instructions one at a time and runs the C code that implements each of them.
python -m dis samples.py prints the bytecode. Here is the part it lists for line 3:
3 LOAD_NAME 2 (print)
PUSH_NULL
LOAD_NAME 0 (batch_size)
LOAD_NAME 1 (steps)
BINARY_OP 5 (*)
CALL 1
POP_TOP
LOAD_CONST 1 (None)
RETURN_VALUELOAD_NAME pushes the value of a name onto a stack of values. BINARY_OP * replaces the top two values with their product, and CALL 1 calls print with one argument. The last three instructions discard what print returned and end the module. These names are CPython 3.14's and change between versions.
One consequence shows up every day. A syntax error is found by the compiler, before any line runs. In this late.py the first line is fine and the second is not:
print("start")
whille True:
pass$ python late.py
File ".../late.py", line 2
whille True:
^^^^^^
SyntaxError: invalid syntax. Did you mean 'while'?start was never printed. (The folder part of the path is shortened to ....) The suggestion "Did you mean 'while'?" is new in 3.14. Every other kind of error happens only when its line executes.
For a file that is imported rather than run, CPython saves the code object in a __pycache__ folder, as samples.cpython-314.pyc, and skips the compiler next time. The topic How CPython runs code opens the loop and the stack properly.
Reading a traceback
When a statement fails, Python raises an exception. If nothing handles it (the topic Files and exceptions shows how), the interpreter prints a traceback and exits with a nonzero status.
This script reports the mean loss of two training runs, and the second run has no losses yet. def defines a function, a named piece of code that runs when it is called; the topic Functions covers them.
def mean(values):
return sum(values) / len(values)
def report(run, losses):
print(run, mean(losses))
report("run A", [0.5, 0.25, 0.75])
report("run B", [])$ python losses.py
run A 0.5
Traceback (most recent call last):
File ".../losses.py", line 8, in <module>
report("run B", [])
~~~~~~^^^^^^^^^^^^^
File ".../losses.py", line 5, in report
print(run, mean(losses))
~~~~^^^^^^^^
File ".../losses.py", line 2, in mean
return sum(values) / len(values)
~~~~~~~~~~~~^~~~~~~~~~~~~
ZeroDivisionError: division by zeroRead it from the bottom.
- The last line says what went wrong: the exception type,
ZeroDivisionError, and its message. - Each
Fileentry is one active call, a frame, with its file, line and function;<module>is the file's top level. The oldest call is at the top and the most recent at the bottom: "most recent call last". The bottom frame is where the exception was raised. - The marks point into the line.
^sits under the operation that failed, here the/, and~under the rest of the expression. - Walk up to find the cause.
meandivided correctly. The empty list came from line 8.
The first line of output matters too: run A finished before run B failed. Statements run in order until one raises.
Tracebacks in the machine-learning courses are long, because the failing line sits deep inside NumPy or PyTorch. The rule is the same: read the last line, then find the lowest frame that is in your own file.
The plan of the course
Here are the four ways to run code side by side.
| REPL | Script | python -m |
Notebook | |
|---|---|---|---|---|
| Start 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 |
| Shows bare expressions | yes | no | no | the last one in a cell |
| State after it ends | lost | lost | lost | kept until the kernel restarts |
The course has six parts. Each topic states a rule exactly, shows a small example with its real output, explains the model underneath and names the mistake that the model predicts.
- Getting started: running code, values and names, control flow, functions, strings and text.
- Data structures: lists and tuples, dictionaries and sets with what each operation costs, iteration and generators, files and exceptions.
- Abstraction: classes, the data model behind
len,+andfor, closures and decorators, modules and environments, type hints. - Reliable code: testing with pytest, debugging and profiling.
- Under the hood: how CPython runs code, writing fast Python, concurrency.
- Scientific Python: NumPy, pandas and Matplotlib.
The Machine Learning course needs the first three parts and NumPy. Deep Learning defines a network as a class whose instances are called like functions, which is the data model of part 3. Parts 4 and 5 are for code that others rely on and that runs fast enough.
Look back at this topic's programs. Every line did one of two things: it created a value, such as 32 or [0.5, 0.25, 0.75], or gave a value a name, such as batch_size. And sys.argv handed us '10', not 10. The next topic, Values, types and names, asks what exactly a value and a name are. Its answer, that a name refers to an object and assignment copies nothing, explains most of the surprises a newcomer to Python meets.
Check your understanding
The same questions as in Pulse. Answers are shared between modes.
Answers are saved on the server and tied to this browser until you sign in.