Python is one of the most popular programming languages in the world. It’s beginner-friendly, readable, and powerful. But have you ever wondered how Python actually runs your code behind the scenes?
In this article, we’ll break down the entire Python code execution process — from the moment you write your code to the moment you see the output on the screen.
Whether you are a beginner or someone brushing up on the basics, this guide will help you understand how Python works internally.
What Happens When You Run a Python File?
Here’s a simplified overview of how Python code gets executed:
Let’s explore each of these steps in detail.
Writing the Source Code
Everything begins when you write a Python program in a .py
file or an interactive shell.
This is called source code. It’s written in human-readable form and must be converted into machine-executable instructions.
Tokenization
The interpreter reads the source code and breaks it into pieces called tokens.
For example, the line:
gets divided into tokens:
-
Identifier:
x
-
Operator:
=
-
Literal:
10
Parsing & AST Creation
The tokens are passed to a parser, which checks if the syntax is valid. If it is, it builds something called an Abstract Syntax Tree (AST) — a tree-like structure that represents your code’s logic.
This tree helps Python understand what you’re trying to do.
Compilation to Bytecode
Next, Python compiles the AST into bytecode. This is a low-level, platform-independent representation of your code. It’s not the same as machine code, but it’s a step closer.
Bytecode is usually stored in a .pyc
file inside the __pycache__
folder.
Python Virtual Machine (PVM)
The Python Virtual Machine (PVM) now takes over. It reads the bytecode line by line and executes it.
This is the heart of the Python interpreter. It’s what actually performs the logic of your code.
Final Output
After PVM executes the bytecode, you finally see the result of your program.
🖥️ Output:
Real Example Breakdown
-
Tokenization: breaks into
x
,=
,5
,y
,=
,10
,print
,(
,x
,+
,y
,)
-
Parsing: creates an AST
-
Bytecode: generated for adding numbers and printing result
-
PVM: executes bytecode and prints:
15
Bonus: See Bytecode with dis
Module
You can even view the bytecode using Python’s built-in dis
module:
It shows exactly what Python is doing behind the scenes.
Understanding how Python code is executed helps you write better, more efficient code. From source code → tokens → AST → bytecode → PVM, each step plays a crucial role in delivering the final output.
Want to become a pro Python developer? Learn not just the syntax, but also the underlying mechanisms.