PYnative

Practice Coding

  • Python â–¼
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Coding Exercises â–¼
    • Python Exercises
    • C++ Exercises
    • C Programming Exercises
    • Java Exercises
    • C# Exercises
  • MCQsâ–¼
    • Python MCQ Quizzes
    • Java MCQ Quizzes
    • C++ MCQ Quizzes
  • Compilersâ–¼
    • Online Python Compiler
    • Online C Compiler
    • Online C++ Compiler
    • Online Java Compiler
    • Online C# Compiler
Home » Python » Basics » How Python Works: Interpreter, Bytecode, and CPython Explained

How Python Works: Interpreter, Bytecode, and CPython Explained

Updated on: December 4, 2026 | Leave a Comment

When you type python hello.py and press Enter, your program runs almost instantly. But how does a computer understand the Python you wrote? It doesn’t understand it directly. Python first translates your code into a simpler form called bytecode, and then runs that bytecode step by step.

You don’t need to know any of this to start writing Python. But a basic picture of what happens helps you understand error messages, explains the mysterious __pycache__ folders that appear in your projects, and answers a common interview question: “Is Python compiled or interpreted?”

In this tutorial, you’ll follow a small program from the moment you run it to the moment it prints its result.

Key terms used in this article:

  • Source code: The Python code you write, saved in a .py file.
  • Machine code: The binary (1s and 0s) instructions that a computer’s processor actually runs.
  • Interpreter: The program that reads your source code and runs it. For Python, this is the python command.
  • Compile: To translate code from one form into another, usually a lower-level one.
  • Bytecode: A simplified set of instructions that Python creates from your source code.
  • Python Virtual Machine (PVM): The part of the interpreter that runs bytecode.

Table of contents

  • Compiled vs interpreted languages
  • What happens when you run a Python program
    • Step 1: Tokenizing
    • Step 2: Parsing
    • Step 3: Compiling to bytecode
    • Step 4: Running on the Python Virtual Machine
  • Why this matters: two kinds of errors
  • What is Python bytecode?
    • See bytecode with the dis module
    • How the PVM runs bytecode
  • .pyc files and the __pycache__ folder
  • What is CPython?
  • Is Python compiled or interpreted?
  • Going deeper (optional)
  • Summary

Compiled vs interpreted languages

A computer’s processor understands only machine code. Every programming language needs a way to turn the code people write into something the computer can carry out. There are two main approaches. Think of translating a book written in a language you don’t speak:

  • Compiled languages (such as C and C++) are like translating the whole book in advance. A compiler converts the entire program into machine code before it runs. The result runs very fast, but you have to translate it again after every change.
  • Interpreted languages are like having a live interpreter read the book aloud to you in your language, sentence by sentence. An interpreter reads the program and carries out each instruction while it runs. You can start immediately, but it’s slower.

Python uses a mix of both. It first translates your code into bytecode, a simpler form that is quick to work with, and then the Python Virtual Machine runs that bytecode. All of this happens automatically when you run python. You never see a separate translation step.

What happens when you run a Python program

Let’s use this two-line program, saved as calc.py:

x = 10 + 5
print(x)Code language: Python (python)

When you run python calc.py, Python takes your code through four steps:

Your code (calc.py)
      │
      â–¼
1. Tokenizing    split the text into small pieces (tokens)
      │
      â–¼
2. Parsing       check the grammar and understand the structure
      │
      â–¼
3. Compiling     translate it into bytecode
      │
      â–¼
4. Running       the Python Virtual Machine runs the bytecode
      │
      â–¼
Output: 15

Steps 1 to 3 happen before the first line of your program runs. Let’s look at each step. You don’t need to memorize the details, just get a feel for what’s going on.

Step 1: Tokenizing

To Python, your file starts out as plain text. The tokenizer splits that text into small meaningful pieces called tokens, just as you split a sentence into words and punctuation. Comments and extra spaces are thrown away here.

You can see the tokens yourself. Run this command in a terminal, in the folder that contains calc.py:

python -m tokenize calc.pyCode language: Python (python)

Output:

0,0-0,0:            ENCODING       'utf-8'
1,0-1,1:            NAME           'x'
1,2-1,3:            OP             '='
1,4-1,6:            NUMBER         '10'
1,7-1,8:            OP             '+'
1,9-1,10:           NUMBER         '5'
1,10-1,11:          NEWLINE        '\n'
2,0-2,5:            NAME           'print'
2,5-2,6:            OP             '('
2,6-2,7:            NAME           'x'
2,7-2,8:            OP             ')'
2,8-2,9:            NEWLINE        '\n'
3,0-3,0:            ENDMARKER      ''

Each row is one token. The middle column shows its type: NAME for names such as x and print, OP for operators and brackets, and NUMBER for numbers. At this point, Python knows what the pieces are, but not yet what they mean together.

Step 2: Parsing

Next, the parser checks that the tokens follow Python’s grammar rules, the same way you’d check that a sentence is grammatically correct. If they do, it works out the structure: “add 10 and 5, store the result in x, then call print with x“.

If the code breaks a grammar rule, for example a missing bracket or quotation mark, the parser stops and reports a SyntaxError. Syntax simply means the rules for how code must be written.

Python stores the structure as a tree called an abstract syntax tree (AST). If you’re curious, you can view it with python -m ast calc.py, but you don’t need to understand it to write Python.

Step 3: Compiling to bytecode

The compiler turns that structure into bytecode: a list of small, simple instructions such as “load this value”, “add these two values”, and “store the result”. You’ll see real bytecode in a moment.

The compiler is also a little clever. It notices that 10 + 5 is always 15, so it stores 15 directly instead of doing the addition every time the program runs.

Step 4: Running on the Python Virtual Machine

Finally, the Python Virtual Machine (PVM) runs the bytecode, one instruction at a time. The PVM isn’t a separate program you install. It’s the part of the Python interpreter that carries out the instructions. This is the step where your program actually does its work and prints 15.

Why this matters: two kinds of errors

Knowing these steps explains something that often confuses beginners: some errors stop your program before it prints anything, while others appear halfway through.

1. Syntax errors are found before anything runs

print("Program started")
print("Hello"Code language: Python (python)

Output:

  File "syntax_demo.py", line 2
    print("Hello"
         ^
SyntaxError: '(' was never closed

Even though line 1 is correct, “Program started” is never printed. Python found the missing bracket on line 2 while parsing (step 2), so it never reached the running step.

2. Runtime errors happen while the program runs

print("Program started")
print(10 / 0)
print("This line never runs")Code language: Python (python)

Output:

Program started
Traceback (most recent call last):
  File "divide.py", line 2, in <module>
    print(10 / 0)
          ~~~^~~
ZeroDivisionError: division by zero

This time, the code is grammatically correct, so it passes steps 1 to 3. Line 1 runs and prints its message. The problem, dividing by zero, is only discovered in step 4 when Python reaches line 2. The program stops there, so line 3 never runs.

What is Python bytecode?

Bytecode is the in-between form of your program: simpler than Python source code, but not yet machine code.

  • It’s quicker for Python to run than re-reading your source text.
  • It isn’t tied to one type of computer, so the same bytecode works on Windows, macOS, and Linux.
  • It can change between Python versions, so bytecode made by one version isn’t used by another.

See bytecode with the dis module

Python includes a module called dis (short for “disassembler”) that shows bytecode in a readable way. Save this program as total.py:

price = 100
qty = 3
total = price * qty
print(total)Code language: Python (python)

Then run this command:

python -m dis total.pyCode language: Python (python)

Output (Python 3.15):

  0           RESUME                   0

  1           LOAD_SMALL_INT         100
              STORE_NAME               0 (price)

  2           LOAD_SMALL_INT           3
              STORE_NAME               1 (qty)

  3           LOAD_NAME                0 (price)
              LOAD_NAME                1 (qty)
              BINARY_OP                5 (*)
              STORE_NAME               2 (total)

  4           LOAD_NAME                3 (print)
              PUSH_NULL
              LOAD_NAME                2 (total)
              CALL                     1
              POP_TOP
              LOAD_COMMON_CONSTANT     7 (None)
              RETURN_VALUE

It looks technical, but it’s easier to read than it seems:

  • The number on the left is the line of your code that the instructions came from.
  • The words in capital letters are the instructions. LOAD means “get a value”, STORE means “save a value under a name”, BINARY_OP means “do a calculation with two values”, and CALL means “call a function”.
  • The text in parentheses, such as (price) or (*), tells you which name or operation the instruction uses.

So line 3, total = price * qty, becomes: get price, get qty, multiply them, and save the result as total.

Note: The exact instructions change between Python versions. If your output looks a little different, for example LOAD_CONST instead of LOAD_SMALL_INT, that’s normal.

How the PVM runs bytecode

The Python Virtual Machine works with a stack: a pile of values where you can only add to the top or take from the top, like a stack of plates. Here’s how it runs total = price * qty when price is 100 and qty is 3:

InstructionWhat it doesStack afterwards
LOAD_NAME pricePut the value of price on the stack[100]
LOAD_NAME qtyPut the value of qty on the stack[100, 3]
BINARY_OP *Take the top two values, multiply them, and put the result back[300]
STORE_NAME totalTake the result and save it under the name total[] (empty)

Every Python program, no matter how large, is broken down into simple steps like these.

.pyc files and the __pycache__ folder

Sooner or later, you’ll notice a folder called __pycache__ appear in your project, containing files that end in .pyc. Here’s what they are.

Translating code into bytecode takes a little time. To save that time, Python stores the bytecode of files you import into other files in .pyc files (“c” for compiled), inside a __pycache__ folder. Let’s see it happen. Create two files in the same folder:

# helper.py
def greet(name):
    return f"Hello, {name}!"Code language: Python (python)
# greet.py
import helper

print(helper.greet("Jessa"))Code language: Python (python)

Run python greet.py. It prints Hello, Jessa!, and a new folder appears:

greet.py
helper.py
__pycache__/
    helper.cpython-315.pyc
  • Only helper.py was saved as bytecode, because greet.py imported it. The file you run directly isn’t saved.
  • cpython-315 in the name means “created by Python 3.15”. Different Python versions keep separate files, so they never mix up each other’s bytecode.
  • Next time, if helper.py hasn’t changed, Python loads the saved bytecode and skips steps 1 to 3. If you edit helper.py, Python notices and creates fresh bytecode automatically.

Note: You never need to open or edit .pyc files, and it’s always safe to delete the __pycache__ folder. Python simply creates it again when needed. If you use Git, add __pycache__/ to your .gitignore file.

What is CPython?

You’ll often see the word “CPython”. It helps to separate two ideas:

  • Python is the language: the rules for how Python code is written and what it means.
  • CPython is the program that runs Python code. It’s the official version of Python, and it’s written in the C programming language, which is where the “C” comes from.

When you download Python from python.org, you get CPython. Everything described in this article is how CPython works. You can check which one you have:

import platform

print(platform.python_implementation())  # CPythonCode language: Python (python)

A few other versions of Python exist for special needs. For example, PyPy can run some programs faster, and MicroPython runs on tiny electronic boards. As a beginner, you only need CPython.

Is Python compiled or interpreted?

This is a popular interview question, and the honest answer is both:

  • Your code is compiled into bytecode, automatically, without a separate step.
  • That bytecode is then interpreted (run) by the Python Virtual Machine.

In everyday conversation, Python is called an interpreted language, because you run your .py files directly and never create a separate program file yourself.

Going deeper (optional)

You can safely skip this section for now and come back to it once you’ve written a few programs. These are topics you’ll hear about as you keep learning:

  • Memory management: Python frees memory automatically. It keeps count of how many variables refer to each value and removes the value when nothing uses it anymore. Learn more in Python Variables.
  • The GIL (Global Interpreter Lock): In the standard version of Python, only one thread can run Python code at a time. This doesn’t affect normal programs. Since Python 3.14, an optional “free-threaded” version without this limit is officially supported.
  • Python is getting faster: Since Python 3.11, the interpreter speeds itself up while your program runs by using faster versions of instructions it sees often. Python 3.13 also added an experimental JIT compiler, which can turn frequently used bytecode into machine code. Upgrading to a newer Python version is often the easiest way to make programs faster.

Summary

  • Computers run machine code. Python translates your code into bytecode, and the Python Virtual Machine runs that bytecode.
  • Running a program has four steps: tokenizing, parsing, compiling to bytecode, and running on the PVM.
  • Syntax errors are found before any of your code runs. Runtime errors, such as dividing by zero, appear only when Python reaches that line.
  • Use python -m dis file.py to see your program’s bytecode.
  • Python saves the bytecode of imported files as .pyc files in a __pycache__ folder so they load faster next time. It’s safe to delete this folder.
  • CPython is the official version of Python that you download from python.org.
  • Python is both compiled (to bytecode) and interpreted (by the PVM), but it’s usually called an interpreted language.

Also, See:

  • What Is Python? History, Features, and Where It’s Used
  • Your First Python Program: Hello World Explained
  • Top 100 Basic Python Interview Questions

Filed Under: Python, Python Basics

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Python Python Basics

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises
Java Exercises
C# Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>

In: Python Python Basics
TweetF  sharein  shareP  Pin

  Python Tutorials

  • Get Started with Python
  • Python Statements
  • Python Comments
  • Python Keywords
  • Python Variables
  • Python Operators
  • Python Data Types
  • Python Casting
  • Python Control Flow statements
  • Python For Loop
  • Python While Loop
  • Python Break and Continue
  • Python Nested Loops
  • Python Input and Output
  • Python range function
  • Check user input is String or Number
  • Accept List as a input from user
  • Python Numbers
  • Python Lists
  • Python Tuples
  • Python Sets
  • Python Dictionaries
  • Python Functions
  • Python Modules
  • Python isinstance()
  • Python OOP
  • Python Inheritance
  • Python Exceptions
  • Python Exercise for Beginners
  • Python Quiz for Beginners

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

All Python Topics

  • Python Basics
  • Python Exercises
  • Python Quizzes
  • Python File Handling
  • Python Date and Time
  • Python OOP
  • Python Random
  • Python Regex
  • Python Pandas
  • Python Databases
  • Python MySQL
  • Python PostgreSQL
  • Python SQLite
  • Python JSON

About PYnative

PYnative.com is a platform built to help developers learn by doing. Solve coding exercises, take MCQs, and run code directly in built-in online compilers.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises
  • Java Exercises
  • C# Exercises

MCQ Quizzes

  • Python MCQs
  • Java MCQs
  • C++ MCQs

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com