Python Mastery – From Basics to Brilliance / Introduction to Python

How Python Code is Executed Internally

An interpreter is a program that reads your Python code line by line and executes it immediately.

Unlike compiled languages like C or Java (which convert the code into machine code before running), Python interprets your code at runtime.

🧠 Python is an interpreted, high-level, dynamically typed language.


🔁 Internal Flow of Python Code Execution

Let’s say you write a file called hello.py with the following content:

print("Hello, Python World!")

When you run it using:

python hello.py

Here’s what really happens behind the scenes:



🧩 Tokenization

Python first breaks your code into tokens (small meaningful chunks) like:

  • Keywords (print)

  • Identifiers

  • Symbols ((), ")

  • Literals ("Hello")

This is handled by Python’s lexer.


🧱 Parsing → AST (Abstract Syntax Tree)

Python checks the syntax of your code and constructs a tree-like structure called the AST.

Think of AST as a blueprint of your program.

If syntax is wrong (e.g. missing parenthesis), Python throws an error at this stage.


🔥 Compilation to Bytecode

Once the AST is ready, Python compiles it to bytecode — a low-level, platform-independent set of instructions that the Python interpreter understands.

Bytecode is stored as .pyc files in the __pycache__ folder.

__pycache__/hello.cpython-311.pyc

✅ Bytecode is not machine code but is portable across systems where Python runs.


🧠 Execution by Python Virtual Machine (PVM)

Now the Python Virtual Machine takes over and executes the bytecode step by step.

This is where your program “actually runs.”

The PVM:

  • Allocates memory for variables

  • Manages function calls

  • Handles exceptions

  • Talks to OS for input/output


📦 Real-World Analogy

Imagine you are ordering food:

  • .py File = Your food order (instructions)

  • Lexer/Parser = The waiter breaking down your order into items

  • AST & Bytecode = The kitchen preparing your order

  • PVM = The chef making and serving it to you

Just like your food goes through steps before it reaches you, Python code goes through multiple stages before being executed.


⚠️ Why Understanding This Helps

  • Helps in debugging and understanding error messages (like syntax errors)

  • Lets you appreciate why Python is slower than compiled languages (it interprets on the fly)

  • Makes you aware of __pycache__ and .pyc files


🧾 Recap:

  • Python code is read and executed line-by-line.

  • Internally, it goes through tokenization → parsing → bytecode compilation → PVM execution.

  • Python is both easy to write and intelligent internally.