EthicsComputerCourses
Join training +91 90532 10052

How Python Runs Your Code

Python · Lesson 2 of 240 Beginner 10 min read Updated

By the end of this lesson you will be able to explain what happens between saving a .py file and seeing its output. You will also know why some errors stop a program before it prints anything, while others appear halfway through.

This knowledge saves real time. When a program fails, knowing when Python found the problem tells you where to look.

The big picture

You write source code: the Python text in your .py file. Your computer's processor cannot understand that text directly. It only understands very simple machine instructions. Something has to sit in the middle, and that something is the Python interpreter, the program you start with the python command.

Think of a Malayalam speaker and a Hindi speaker meeting in Kochi with a translator. The translator listens, understands and passes the meaning on. The interpreter does the same job between your code and the processor.

When you type python bill.py, three things happen in order:

  1. Check: Python reads the whole file and checks its grammar (the syntax).
  2. Translate: Python turns the code into bytecode, a list of small, simple instructions.
  3. Run: the Python virtual machine carries out the bytecode, one instruction at a time.

Steps 1 and 2 are fast and invisible. You only notice them when something goes wrong. The rest of this lesson walks through each step.

Step 1: Python checks the whole file first

Before running a single line, Python reads the complete file and checks its grammar. This is called parsing. If any line breaks the rules from Python Syntax, Python stops right there, and nothing runs, not even the lines above the mistake.

Look at this small program. The last line is missing its closing bracket:

Python
print("Billing started")
tea = 120
print("Total:", tea + 45

You might expect "Billing started" to appear first. It does not. This is the complete output:

Output
  File "C:\Users\meera\practice\bill.py", line 3
    print("Total:", tea + 45
         ^
SyntaxError: '(' was never closed

The first line was perfectly fine, but Python never reached the "run" step, because the file failed the check. A SyntaxError always means "this file is not valid Python", so fix it before anything else.

Python has a built-in function, compile(), that does only the check-and-translate part without running anything. You can use it to see the check happen by itself:

PythonRun in editor
source = 'print("Namaste"'

try:
    compile(source, "check.py", "exec")
    print("No syntax errors found")
except SyntaxError as error:
    print("Line", error.lineno, "has a problem:", error.msg)

code = compile('print("Namaste")', "check.py", "exec")
exec(code)
Output
Line 1 has a problem: '(' was never closed
Namaste

The first compile() fails the check, so the except part reports the problem. The second one passes, and exec() then runs the translated code. You will learn try and except properly in Errors & Exceptions; here they simply catch the error so the program can print a message. You will rarely call compile() yourself, but Python does exactly this every time you run a file.

Step 2: Python turns your code into bytecode

Once the file passes the check, Python translates it into bytecode. Bytecode is not machine code for your processor. It is a set of small, simple instructions designed for Python's own engine.

An everyday comparison: a recipe says "make masala chai". A new kitchen helper needs it in tiny steps: boil water, add tea leaves, add milk, add sugar, strain. Bytecode is that tiny-steps version of your program.

The dis module (short for "disassemble") lets you look at the bytecode for any piece of code:

PythonRun in editor
import dis

dis.dis("total = price * 2")
Output
0           RESUME                   0

1           LOAD_NAME                0 (price)
            LOAD_SMALL_INT           2
            BINARY_OP                5 (*)
            STORE_NAME               1 (total)
            LOAD_CONST               1 (None)
            RETURN_VALUE

You do not need to memorise any of this. Just notice the idea: one line of Python became several small instructions. "Load the value of price", "load the number 2", "multiply them", "store the result in total". The exact instruction names can change between Python versions, so the output on Python 3.15 may look slightly different.

Step 3: The virtual machine runs the bytecode

The Python virtual machine (often called the PVM) is the part of the interpreter that carries out bytecode instructions in order. "Virtual machine" here just means a program that acts like a simple computer, with its own instruction set.

Because the instructions run one after another, errors that depend on values are only discovered when Python reaches them. These are runtime errors. Here the name gst was never created:

Python
print("Booking ticket for Priya")
fare = 755
print("Fare:", fare)
print("With GST:", fare + gst)
print("Booking complete")
Output
Booking ticket for Priya
Fare: 755
Traceback (most recent call last):
  File "C:\Users\meera\practice\ticket.py", line 4, in <module>
    print("With GST:", fare + gst)
                              ^^^
NameError: name 'gst' is not defined

This time the first two lines did print. The grammar was fine, so the file passed the check and started running. Python only discovered the missing name on line 4, then stopped. Line 5 never ran. You will learn to read these messages fully in Reading Error Messages & Tracebacks.

So there are two kinds of failure:

When it is foundExampleDoes any output appear first?
Before running (the check)SyntaxError, IndentationErrorNo, nothing runs
While runningNameError, TypeError, ZeroDivisionErrorYes, every line before the error runs

Where .pyc files and __pycache__ come from

Sooner or later you will see a folder named __pycache__ appear next to your files. It appears when one of your files imports another one (you will learn imports in Modules & Imports). For example, if shop.py contains import prices, Python saves the bytecode of prices.py so it can skip the check-and-translate steps next time:

Text
practice/
├── __pycache__/
│   └── prices.cpython-314.pyc
├── prices.py
└── shop.py

The .pyc file is the saved bytecode. The name records which Python made it: cpython-314 means CPython 3.14, and Python 3.15 writes cpython-315. If you change prices.py, Python notices and rebuilds the .pyc automatically.

The file you run directly (here shop.py) is translated fresh every time and is not cached. You can delete __pycache__ at any time; Python simply makes it again. Teams add it to .gitignore, as you will see in the Git course.

CPython and other Pythons

The interpreter you download from python.org is called CPython, because it is written in the C language. When people say "Python", they almost always mean CPython. Other implementations run the same language in different places:

  • PyPy: a Python that can run long programs faster using a JIT (just-in-time) compiler.
  • MicroPython: a small Python for microcontroller boards.
  • Pyodide: CPython compiled to WebAssembly so it runs inside a web browser. The "Run" button on this site uses it.

You can ask Python which implementation and version is running your code:

PythonRun in editor
import sys

print(sys.implementation.name)
print(sys.version_info.major, sys.version_info.minor)
Output
cpython
3 14

In the browser this prints 3 14, because the runner uses Python 3.14. On your own computer with Python 3.15 you will see 3 15. If you also print sys.platform, the browser shows emscripten while Windows shows win32: same language, different machine underneath.

Common mistakes

  • Expecting lines above a SyntaxError to run. They never do. A syntax error anywhere in the file stops the whole file.
  • Thinking a .pyc file hides your code. Bytecode can be turned back into readable Python quite easily. It is a speed cache, not protection.
  • Committing __pycache__ to Git. It is generated, differs between Python versions and only adds noise. Ignore it.
  • Reading only the first line of an error. The last line names the problem, and the File ... line part tells you where.

Interview questions

1. Is Python a compiled or an interpreted language?

CPython does both. It first compiles source code into bytecode, then its virtual machine interprets the bytecode instruction by instruction. It does not compile to native machine code ahead of time the way C does.

2. What is a .pyc file and when is it created?

A .pyc file stores the compiled bytecode of a module. CPython writes it into __pycache__ when a module is imported, so later imports can skip parsing and compiling. The main script you run is not cached this way.

3. Why does a SyntaxError prevent any output, while a NameError appears after some output?

Syntax is checked for the whole file before execution starts, so a syntax error stops everything. A NameError is a runtime error, found only when the virtual machine reaches that line, so earlier lines have already run.

4. What is CPython, and name one other implementation?

CPython is the reference implementation of Python, written in C and distributed by python.org. Others include PyPy (with a JIT compiler), MicroPython (for microcontrollers) and Pyodide (CPython compiled to WebAssembly for browsers).

Key points

  • The interpreter checks the whole file, translates it to bytecode, then runs the bytecode.
  • A SyntaxError is found during the check, so no line of the file runs.
  • Runtime errors such as NameError appear when Python reaches the line, after earlier lines have run.
  • dis.dis() shows bytecode; compile() checks and translates without running.
  • Imported modules are cached as .pyc files in __pycache__, which is safe to delete and should not be committed.
  • CPython is the standard interpreter; PyPy, MicroPython and Pyodide are other implementations.

Exercise

Without running them, predict the complete output of both programs below. Write down whether each one fails during the check or while running. Then run them on your computer (or paste them into the editor) and compare.

Program A, saved as a.py:

Python
print("Rohan's score card")
runs = 48
if runs > 50
    print("Half century!")

Program B, saved as b.py:

Python
print("Isha's score card")
runs = 48
print("Strike rate:", runs / balls)
print("Done")
Show solution

Program A has a missing colon after if runs > 50, so it fails the check. Nothing prints except the error:

Output
  File "C:\Users\meera\practice\a.py", line 3
    if runs > 50
                ^
SyntaxError: expected ':'

Program B passes the check and starts running. The first line prints, then Python reaches balls, which was never created:

Output
Isha's score card
Traceback (most recent call last):
  File "C:\Users\meera\practice\b.py", line 3, in <module>
    print("Strike rate:", runs / balls)
                                 ^^^^^
NameError: name 'balls' is not defined

A syntax error stops the whole file; a runtime error stops at the line where it happens.

Quick Quiz

1. A file has a syntax error on its last line. What happens to the print() on its first line?

2. What is bytecode?

3. When does Python create a .pyc file in __pycache__?

4. Which statement about __pycache__ is true?

Learn Python with a mentor

Free lessons get you started. Our Python Programming training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call