⚙️ What Happens When You Run a .py File

When you type python hello.py, the Python interpreter doesn't directly execute your code. Instead, it travels through three stages: reading the source code, translating it to bytecode, then executing it on the Python Virtual Machine (PVM).

Source Code → Bytecode → PVM

This journey—unlike compiled languages like C where the entire file becomes a binary before running—happens on-demand. Python reads and compiles what it needs, when it needs it. That's why Python is called "interpreted."

Understanding this three-stage process is the key to debugging slow code, deploying Python to production, and knowing why Python feels both easy and fast for AI work.

🔧 5 Key Components in Python Execution

Source Code
hello.py
Your .py file in plain English-like syntax.
Interpreter
CPython
Reads, parses, and translates source to bytecode.
Bytecode
.pyc files
Intermediate, machine-readable instructions.
PVM
Virtual Machine
Executes bytecode line by line (stack-based).
Memory
Heap + Stack
GC cleans objects when no longer used.

📍 A Real Scenario: Aisha in Nairobi Runs Her First Script

🇰🇪
Nairobi · Aisha's Laptop
Learning Python, Debugging Why Code Runs Fast

Aisha just finished writing her first Python script on her MacBook in Nairobi. It reads a list of M-Pesa transactions and calculates the average. She types python transactions.py and it runs instantly—taking 0.2 seconds. She wonders: Did Python compile my code first? Where does the 0.2 seconds go? Where are the compiled files?

In that 0.2 seconds, three things happened that Aisha didn't see. The interpreter parsed her code, compiled it to bytecode, stored it (invisibly), and executed it on the PVM. If she runs the script again, it's faster because Python reuses the bytecode. If she'd written the same script in C, she'd manually compile it first—a separate step. Python hides compilation from you.

0.2s
First run (compile + execute)
0.15s
Second run (reuse bytecode)
KSh 100
Avg M-Pesa transaction

🚀 Step-by-Step: Running a Python Script

Let's trace what happens when you run a simple "hello" program. Here's the journey in 4 stages.

Stage 1: Source Code (What You Write)

hello.py ▶ Your original file

Stage 2: Parsing & Compilation to Bytecode

The interpreter reads your source code and translates it into bytecode—a low-level, portable instruction set. Python stores this in .pyc files (bytecode cache) inside a __pycache__/ folder.

Bytecode (CPython) ▶ What the interpreter creates

This bytecode is stored in __pycache__/hello.cpython-39.pyc (the version number depends on your Python version). You never see these files normally—Python manages them automatically.

Stage 3 & 4: PVM Execution

The PVM (Python Virtual Machine) reads each bytecode instruction, one by one, and executes it. It manages a call stack (for function calls), a heap (for objects like lists and strings), and references to built-in operations.

# Output (what you see) M-Pesa total: KSh 600

Key insight: The bytecode is portable. The same .pyc file can run on any machine that has a PVM installed—Windows, Linux, or a Raspberry Pi in a warehouse in Mumbai. That portability is why Python runs everywhere.

🔀 Interpreted vs. Compiled: The Real Difference

Python is interpreted—but not in the way you might think. The truth is more nuanced and explains why Python feels slow for tight loops but fast for data science.

What "Interpreted" Really Means

An interpreted language compiles source code to bytecode on-the-fly and executes it immediately (or caches the bytecode). A compiled language compiles the entire source to machine code upfront, producing an executable binary that you run separately.

Comparison: Python vs. C vs. Java

Workflow comparison ▶ Read carefully

Why this matters in practice:

  • Python: Faster feedback loop (no compile step = faster iteration). Slower at runtime (bytecode → PVM is slower than machine code).
  • C: Slow feedback (must compile before running). Faster at runtime (machine code runs at CPU speed).
  • Java: Hybrid approach—compile once, run anywhere (like Python), but with more upfront compilation overhead.

The Python trick for speed: Core libraries (NumPy, PyTorch) are written in C and called from Python. You get Python's ease + C's speed. This is why import numpy as np then calling np.dot(A, B) is fast—the heavy math runs in compiled C code, not bytecode.

🔒 The Global Interpreter Lock (GIL) in One Sentence

The GIL ensures only one thread executes Python bytecode at a time, even on multi-core CPUs—so multi-threaded Python doesn't get true parallelism, but it's fine for IO-bound work (web requests, file reads) since threads pause when waiting for IO.

Practical takeaway: For CPU-bound work (loops, math), use multiprocessing instead of threading. For IO-bound work (API calls, databases), threading or asyncio is fine.

💾 Memory Management Basics

Python uses automatic garbage collection. You don't manually free memory like in C (where you call free()). Instead, Python tracks references to objects.

Two-part memory system

📚
Stack
Stores local variables and function calls (fast, limited size)
🏗️
Heap
Stores objects like lists, dicts, strings (slower, large, garbage-collected)

Example:

memory_example.py ▶ Reference counting

Python uses reference counting: when no variables point to an object, Python's garbage collector automatically frees it. This is efficient for most programs but can cause issues in circular references (which Python's cycle detector handles).

🎯 Why Understanding Python's Execution Matters

Real-world impact

⚡
Speed
Know why tight loops in Python are slow (bytecode overhead), but NumPy is fast (C code). Choose the right tool for the job.
🚀
Deployment
Python ships source code + bytecode cache. No "compilation step" before production—just upload .py files and run. Compare this to C where you must compile for your OS.
🐛
Debugging
When a script crashes, Python shows you the line in your source code (not bytecode). The PVM keeps that connection for you.
📦
Portability
Same .py file runs on Windows, Linux, Mac, and Raspberry Pi—as long as a Python interpreter is installed. Compiled binaries must be recompiled for each OS.

🤖 How AI/ML Uses Python's Execution Model

When you train a machine learning model with PyTorch or TensorFlow, you write Python code that describes the computation graph. The interpreter compiles your Python to bytecode, and then the framework's C/CUDA backend (which you never see) executes the heavy math on GPU. You get Pythonic syntax with GPU speed. This is exactly why Python dominates AI—you describe what you want in simple code; the framework handles the fast execution. Understanding the three-stage execution (source → bytecode → runtime) helps you know where optimizations happen: in the framework's C/CUDA layers, not in your Python syntax.

PyTorch TensorFlow scikit-learn CUDA JIT Compilation

🎯 Mini Challenge: Inspect the Bytecode

Decode Real Bytecode Output

Open a Python terminal and run: python -c "import dis; dis.dis('x = 1 + 2')"

What you'll see: A list of bytecode instructions (LOAD_CONST, BINARY_ADD, STORE_NAME, etc.). Try to match each instruction to what it does in your calculation.

LOAD_CONST 1: Push the number 1 onto the stack. LOAD_CONST 2: Push 2 onto the stack. BINARY_ADD: Pop 2 and 1, add them, push 3 back. STORE_NAME: Pop 3 and store it in variable x. The PVM is stack-based—everything is push/pop operations. This is identical to how the bytecode in the tutorial is structured.

🎤 Interview Questions

Both. Python compiles source code to bytecode (stored in .pyc files) and interprets that bytecode at runtime via the PVM. This is a hybrid approach. Unlike pure compiled languages (C), you don't manually run a compiler. Unlike pure interpreted languages (old shell scripts), Python caches the bytecode for speed.
The PVM is a stack-based interpreter that executes Python bytecode. It's a program (written in C) that reads each bytecode instruction and performs the corresponding operation: push/pop values, call functions, allocate memory. Every Python interpreter (CPython, PyPy, Jython) has its own PVM implementation, but they all understand the same bytecode format.
Bytecode is intermediate code between human-readable Python and machine code. It's portable (same .pyc works on any OS) but not human-readable. Python stores bytecode in __pycache__/module.cpython-.pyc files automatically. You rarely touch these files—Python manages them. If you delete them, Python regenerates them the next time you import or run the code.
The term "interpreted" refers to the user experience, not the technical process. With compiled languages (C), you run the compiler yourself—a separate step. With interpreted languages (Python), the interpreter handles compilation automatically and invisibly before execution. So from a user's view, you just run python script.py and it works—no compilation step. The interpreter does the compiling for you behind the scenes.
Because the heavy computation is not in Python. When you call torch.matmul(A, B), that's a Python function that immediately delegates to a C/CUDA function in the PyTorch backend. Your Python bytecode only handles the orchestration (loading data, setting hyperparameters, logging results)—the computation runs in compiled C or GPU kernels. This is why NumPy and PyTorch beat pure-Python loops by 100–1000x. You write Pythonic code but get C/GPU speed.

🧠 Quick Quiz

Question 1 of 5
What are the three stages of Python execution?
Question 2 of 5
Where does Python store bytecode?
Question 3 of 5
Why is the PVM called "stack-based"?
Question 4 of 5
In one sentence, what is the GIL?
Question 5 of 5
Why are NumPy and PyTorch fast despite running on Python?
0
/5

📋 Python Execution Cheatsheet

StageWhat HappensOutput/Format
1. Source CodeYou write .py filePlain text, human-readable
2. CompilationInterpreter parses and translates.pyc bytecode (cached)
3. PVM ExecutionStack-based VM executes bytecodeProgram output + side effects
GILOnly one thread runs bytecodeUse multiprocessing for CPU parallelism
MemoryAutomatic garbage collectionReference counting, cycle detection
File Extension.py is source.pyc is bytecode (auto-cached)
InterpretersCPython (most common), PyPy, JythonAll produce same bytecode
PortabilitySame .pyc runs on any OSNo recompilation needed
Speed TrickNumPy/PyTorch delegate to C/CUDAPython syntax + compiled speed

⚠️ Common Misconceptions

"Python is interpreted, so it's not compiled"
False. Python compiles to bytecode (you just don't see it). The difference is when compilation happens: Python does it automatically; C forces you to do it manually upfront.
".pyc files are executables"
No. .pyc files are bytecode cache, not binaries. You can't run them directly. The PVM must be installed to execute them. They're just a speed optimization—Python regenerates them if deleted.
"Python runs slowly because it's interpreted"
Partially true. Pure Python loops are slow (bytecode overhead). But NumPy, PyTorch, and Pandas run fast because the heavy work is in compiled C/CUDA, not Python. Don't use pure Python for math—use the right library.
"The GIL makes Python multithreading useless"
False. The GIL only prevents bytecode parallelism. Multi-threading still works great for IO-bound tasks (web requests, file reads) because threads pause during IO, letting other threads run. Use multiprocessing only for CPU-bound work.

✦ Key Takeaways

  • Python compiles to bytecode automatically, then the PVM executes it line by line
  • Bytecode is cached in __pycache__/ for speed; subsequent runs reuse it
  • Python is called "interpreted" because compilation is automatic and hidden, unlike C
  • The PVM is stack-based: bytecode instructions push/pop values for computation
  • The GIL limits multithreading to one thread executing bytecode at a time
  • Python's memory is automatically garbage-collected via reference counting
  • NumPy and PyTorch are fast because they call compiled C/CUDA code, not because Python is optimized
  • Portability is a superpower: same .py / .pyc runs on Windows, Linux, Mac, and Raspberry Pi
Africa & India's Best AI Academy
🤖 AI-first 🎓 Placement Assistance

From bytecode to production.
Build real AI projects.

Join the Best AI Program: The AI-Era Analyst — 5 months, fully online, with placement assistance. Week 1 is free.

Explore The AI-Era Analyst →