Built with Tutify.io

    AIStudyLabs

    How Python Executes Code

    How Python Executes Code

    Introduction

    In earlier lessons, you learned how to install Python and run your first scripts. In this lesson, you’ll look inside the black box and see how Python actually runs your code. You’ll learn what the interpreter does, how Python turns your .py files into something it can execute, what bytecode and .pyc files are, and how interactive mode differs from running full scripts. You’ll also see how Python handles errors along the way.

    Understanding this execution model will help you reason about performance, debugging, and why some errors appear only at runtime.


    The Python Interpreter: From Source Code to Running Program

    When you run a Python file, the interpreter doesn’t execute your text directly. It goes through several steps:

    1. Read your source code (.py file)
    2. Parse it into a syntax tree
    3. Compile it to bytecode
    4. Execute the bytecode in the Python Virtual Machine (PVM)

    Let’s walk through these at a high level.

    1. Parsing: Understanding Your Code Structure

    Parsing is where Python checks if your program is syntactically valid and builds an internal representation of it.

    2. Compilation: Source Code → Bytecode

    If parsing succeeds, Python compiles the syntax tree into bytecode:

    You can see the bytecode for a simple function using the dis module:

    import dis
    
    def add(a, b):
        return a + b
    
    dis.dis(add)
    
    # output (simplified and may differ slightly by version)
      4           0 LOAD_FAST                0 (a)
                  2 LOAD_FAST                1 (b)
                  4 BINARY_ADD
                  6 RETURN_VALUE
    

    Here, LOAD_FAST, BINARY_ADD, and RETURN_VALUE are bytecode instructions the VM will execute.


    Bytecode and .pyc Files

    To avoid recompiling the same file every time, Python caches compiled bytecode in .pyc files:

    How .pyc Fits into Execution

    When you run a module:

    1. Python checks if a valid .pyc file already exists.
    2. If yes and it matches the current source (based on timestamps), Python loads the bytecode directly.
    3. If no (or outdated), Python recompiles the .py file, executes it, and updates/creates the .pyc file.

    This is why the first run of a large program may be slightly slower than subsequent runs.

    High-Level Execution Flow in the Python VM

    Once bytecode is ready (from a script or interactive input), the Python Virtual Machine:

    1. Loads the bytecode into a new frame (execution context)
    2. Initializes the module’s global namespace (variables, functions, imports)
    3. Executes bytecode instructions sequentially
    4. Manages function calls, loops, and control flow by jumping between bytecode instructions

    Example:

    # flow_example.py
    
    def greet(name):
        message = f"Hello, {name}!"
        return message
    
    user = "Python"
    print(greet(user))
    
    # output
    Hello, Python!
    

    Under the hood:


    Script Execution vs Interactive Mode (REPL)

    Python can execute code in two main ways:

    What is the REPL?

    The REPL repeatedly performs four steps for each line you enter:

    1. Read: take your input line (or block)
    2. Eval: parse and compile it, then execute it
    3. Print: display the result (if any)
    4. Loop: wait for the next input

    Example (imagine this typed into the Python prompt):

    >>> x = 10
    >>> x + 5
    15
    >>> print(x * 2)
    20
    
    # output
    15
    20
    

    The REPL is great for:

    Script Execution

    In script mode, Python:

    1. Reads the entire file
    2. Parses and compiles it (possibly using .pyc cache)
    3. Executes top-to-bottom in a new module namespace

    Example script:

    # script_example.py
    
    x = 10
    
    def multiply_by_two(n):
        return n * 2
    
    result = multiply_by_two(x)
    print("Result:", result)
    

    If you run python script_example.py:

    # output
    Result: 20
    

    You typically use scripts (or modules) for:

    In practice, many developers prototype in the REPL and then move stable code into scripts.


    Summary / Key Takeaways

    In this lesson How Python Executes Code: Interpreter and Execution Model, you have learned:

    Python Beginner Tutorial with Examples — Getting Started with Python and the Course

    Getting Started with Python and the Course

    Python Basics

    Control Flow in Python

    Data Structures in Python

    Functions and Scope in Python

    Error Handling and Debugging

    Working with Libraries

    Script Writing and Automation

    Real-world Applications of Python

    Advanced Python Concepts

    Best Practices in Python

    Tutorial Not Found