Introduction to Computer Science/2.10 Compilers and Interpreters

2.10 Compilers and Interpreters

šŸŽÆ Learning Goals for This Page
  • Define "source code" and "machine code."
  • Explain the role of a compiler in translating code.
  • Explain the role of an interpreter in translating code.
  • Identify Python as an interpreted language.

How Does a Computer Understand Our Code?

We have a puzzle. We know that we write code in Python (source code), which looks like English. But we also know that the CPU only understands 1s and 0s (machine code). So how does our Python code actually get executed by the CPU? The answer is that we need a special program to act as a translator. There are two main types of translators: compilers and interpreters.

🌐

Analogy: The Language Translator

Imagine you need to translate a book from English to French. You have two options:

  • Option A (The Compiler): You give the entire English book to a translator. They work for a while and come back to you with a completely translated French book. You then give this new book to the French reader.
  • Option B (The Interpreter): You, the translator, and the French reader all sit in a room together. You speak one sentence in English. The translator immediately translates it aloud. The reader hears it. You speak the next sentence, and the process repeats. It's a live, line-by-line translation.

The Two Types of Translators

Compiler

A compiler reads your entire program at once, checks for errors, and translates it into a standalone executable file (for example, an .exe on Windows). You then run that executable file. Languages like C++ and Java use compilers.

  • Pro: The final program usually runs very fast.
  • Con: There’s a separate ā€œcompileā€ step before you can run it.

Interpreter

An interpreter goes through your code line by line, translating and running each line as it goes. It doesn’t create a separate executable file. Python is (mainly) interpreted.

  • Pro: Great for quick testing and debugging—run code instantly.
  • Con: Can be slower to run than compiled programs.

Did you know? CPython (the standard Python) first compiles your .py to bytecode (.pyc), then a bytecode interpreter runs it. That’s why Python feels ā€œinterpreted,ā€ but there is a tiny compile step under the hood.


Visualizing the Difference

This short video gives a clear, beginner-friendly summary of compilers vs. interpreters.

Why This Matters

Understanding that Python is an interpreted language helps explain why we can just click ā€œRunā€ and see results immediately. Under the hood, CPython compiles your code to bytecode, then a bytecode interpreter executes it—live, one step at a time.

Further reading

Interactive Sandbox

Use this space to practice writing code and complete the "Your Turn" activities above.

Python 3Initializing...
Loading code editor...
Program output will appear here...