Sub topic 1
What Python is and how a Python program runs
Prerequisites
This chapter assumes you can do the following:
- Open a terminal or command prompt and type a command.
- Install ordinary software on your computer.
- Read a few lines of code in any language, even if you have never written Python.
You do not need Python installed to read most of this chapter. The code samples are for when you finish installing it in later chapters. Come back to them then.
What Python is
Python is a general-purpose programming language. You write instructions as plain text, and a program called the interpreter carries them out. The language is the set of rules for what your text means. The interpreter is the software that follows those rules on your machine.
This difference explains many setup problems. Installing Python means installing an interpreter, plus its standard library (a large collection of ready-made modules such as json, pathlib, and sqlite3) and a few tools such as pip. When someone says "run this with Python," they mean "give this file to an interpreter."
Python is also dynamically typed and garbage collected. Variables do not declare types, and memory is reclaimed for you. Neither fact matters for installation, but both help explain why Python programs are short and why they run slower than compiled languages such as C or Rust.
Which Python you are installing
Several interpreters implement the language. Almost everyone means CPython, the reference implementation written in C and distributed from python.org. Unless a tutorial says otherwise, "Python" means CPython.
| Implementation | What it is | When you meet it |
|---|---|---|
| CPython | The reference interpreter, written in C | Default on python.org, most Linux distributions, and Homebrew |
| PyPy | An alternative interpreter with a just-in-time compiler | Long-running, CPU-heavy programs |
| MicroPython | A small interpreter for microcontrollers | Embedded boards |
| Jython and IronPython | Interpreters for the Java and .NET platforms | Legacy integration work |
The rest of this tutorial uses CPython 3. Python 2 reached end of life in 2020. If a guide tells you to type python and your system answers with a 2.x version, the system is out of date or the guide is.
The working model: from text to behavior
The common description, "Python is interpreted," leaves out a step. CPython does not read your text line by line and act on each line as it goes. It first compiles the whole file, then executes the result.
- Read and parse. The interpreter reads the source file and turns the text into a structure that represents the program. If the text breaks the grammar, you get a
SyntaxErrorand nothing runs. - Compile to bytecode. The structure becomes bytecode, a compact list of low-level instructions for an imaginary machine. Bytecode is internal to CPython. It is not machine code, and it can change between Python versions.
- Execute on the virtual machine. The Python virtual machine (PVM) is a loop inside the interpreter. It takes one bytecode instruction at a time and performs it.
You can look at bytecode yourself with the standard dis module:
import dis
def add(a, b):
return a + b
dis.dis(add)The output lists instructions such as LOAD_FAST (push a local variable onto the stack) and an addition instruction. The exact names and layout depend on your Python version, so do not rely on them. The point is that a + b has become a short sequence of stack operations.
Where bytecode is cached
When your program imports a module, CPython saves the compiled bytecode in a __pycache__ folder next to the module. Files in it end in .pyc, for example helpers.cpython-312.pyc. The next run skips compilation if the source file has not changed. CPython checks this using the source file's modification time and size, which are stored inside the .pyc file.
Three details are worth knowing:
- The script you run directly is not cached. Only modules it imports are. Running
python3 hello.pynever createshello.cpython-312.pyc. - The version tag in the filename keeps different Python versions from reading each other's bytecode.
__pycache__is safe to delete and should not go into version control. The interpreter rebuilds it when needed.
Caching affects startup time only. It does not make your running code faster.
Running code: two ways in
You will use two modes constantly, and they behave differently.
- The REPL (read-evaluate-print loop) starts when you run
python3with no file. You type a statement, Python compiles and runs it immediately, and it prints the value of an expression. It is best for trying small ideas. - A script is a file ending in
.pythat you pass to the interpreter. The whole file is compiled first, then run from top to bottom. Scripts are how real programs are run.
Both modes use the same interpreter and the same language. The only difference is where the source text comes from. Later chapters cover each mode in detail.
Top to bottom: what "run" means
A Python file does not have a special entry point like main in C or Java. The interpreter executes each top-level statement in order. A def statement does not run the function. It creates a function object and binds it to a name. The body runs only when something calls it.
print("1. before the function is defined")
def greet():
print("3. inside the function")
print("2. after the function is defined")
greet()Running this prints the numbers in order 1, 2, 3. If you moved the greet() call above the def, you would get a NameError, because the name does not exist yet when that line executes. This is the single most common surprise for people coming from languages that hoist definitions.
Modules and the `__name__` variable
Every .py file is a module. When you run a file directly, Python sets a built-in variable named __name__ to the string "__main__". When another file imports it, __name__ is the module's own name instead.
Create a file named whoami.py:
import sys
print("Interpreter version:", sys.version.split()[0])
print("Interpreter path:", sys.executable)
print("This module's __name__ is:", __name__)Run it directly and it prints __main__. Start the REPL in the same folder and type import whoami, and the same lines run during the import, printing whoami. This is why scripts that you want to import without side effects use the if __name__ == "__main__": guard, which a later chapter covers.
The sys.executable line is the quickest way to answer "which Python is actually running this?", a question that matters whenever several versions are installed.
Common errors and what they mean
Most first-day failures fall into a few categories. Knowing when each one happens tells you where to look.
| Symptom | When it happens | Usual cause |
|---|---|---|
| `SyntaxError` | Before any code runs | Invalid grammar, such as a missing parenthesis or a bad indent |
| `NameError` or `TypeError` | While the program runs | A misspelled name, or an operation on the wrong kind of value |
| `ModuleNotFoundError` | During an `import` | The package is not installed in the interpreter that is running |
| `command not found` or `'python' is not recognized` | In the terminal, before Python starts | Python is not installed or its folder is not on `PATH` |
The timing distinction is useful. Take a file with a typo on its last line:
print("start")
total = (1 +This prints nothing, not even start. The compile step fails on the whole file before the first statement runs. Now compare a file with a runtime error:
print("start")
print(undefined_name)This prints start and then fails with a NameError. A SyntaxError means the interpreter rejected the whole file. A runtime error means the program ran up to the failing line.
Shadowing a standard module
One error is specific to how imports work. When you run a script, Python puts the script's folder first in its module search path. If you name your file random.py or json.py, then import random inside any script in that folder loads your file instead of the standard library module. The usual symptoms are an AttributeError mentioning your own file, or a circular import error. Rename the file and delete the stale __pycache__ folder next to it.
One machine, several interpreters
Because the interpreter is just a program, you can have many installed at once: a system Python, one from python.org, one from Homebrew, and one per virtual environment. The python3 command in your terminal runs one specific executable, found by searching the folders listed in PATH. A package installed for one interpreter is invisible to the others. Many "I installed it but I can't import it" problems come from this mismatch, not from a broken installation. Running python3 -c "import sys; print(sys.executable)" tells you which interpreter answered.
How this chapter connects to the rest
The next chapters follow the order a new user needs. You choose a version, install it, and confirm that your terminal finds it. Then you use the REPL, write and run a script, and read tracebacks. Finally you isolate a project in a virtual environment. Each step applies the model above: some interpreter, found through PATH, compiles your text to bytecode and runs it.
Exercise
You run python3 report.py. The file contains print("Starting") on line 1 and an unclosed parenthesis on line 20. Does "Starting" appear on screen? Explain using the compile and execute steps.
Show answer
No. CPython compiles the whole file to bytecode before executing any of it. The unclosed parenthesis causes a SyntaxError during the compile step, so the virtual machine never starts and line 1 never runs.
Exercise
You create a file called random.py next to a script that contains import random, and the script now fails with an AttributeError. What is happening, and how do you fix it?
Show answer
Python puts the script's folder first on the module search path, so import random loads your own random.py instead of the standard library module. Rename your file to something that is not a standard module name, and delete the __pycache__ folder beside it.
Exercise
After running python3 helpers_main.py, you see a __pycache__ folder, but it has no file for helpers_main. The script imports a module named helpers. Why is only helpers cached?
Show answer
CPython caches the bytecode of imported modules only. The script you run directly is compiled in memory on every run and is not saved as a .pyc file.