Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 0.8 — How Python Really Runs Your Code
Python · Example 1 of 3

Compile, then run: the two steps by hand

The source says 2 + 3 but the compiled constants contain 5: the compiler did the sum in advance.

When you run a file, Python first compiles your source code into bytecode, a compact set of simple instructions, and then a virtual machine carries those instructions out one by one. The standard Python that does this is called CPython; knowing these steps explains Python's error behaviour and its speed.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Use compile() and co_consts to show what the compiler stores for the source "x = 60 * 60 * 24".

02

Write a program that prints Running on CPython if platform.python_implementation() is "CPython", and Running on something else otherwise.

03

A file has a SyntaxError on line 50 and a print("start") on line 1. What appears when you run it, and why?

Explain it without notes

01

What are the two steps Python performs when you run a file?

02

Why does a syntax error on the last line stop the first line from running, while a NameError on the last line does not?

03

What is CPython, and how does it relate to PyPy and Pyodide?

04

What is in __pycache__, and what happens if you delete it?

05

Give two reasons pure Python code runs slower than C, and two ways Python programs avoid the problem.

Compile, then run: the two steps by hand
Sign in to run this example in your browser.

Expected output

code
(5, None)
('print',)
20 bytes of bytecode
5