Skip to content
KALANBLON
Show contents

Chapter 5 of 7 · 20 min

From code to program

By the end of this chapter, you'll be able to

  • Place machine code, assembly and high-level languages
  • Tell compilation and interpretation apart
  • Observe the bytecode Python produces from your code
  • Explain the role of the operating system

Languages that get more and more human

  • Machine code is the processor's language: instructions encoded as numbers, specific to each processor family (x86 for most desktop computers, ARM for phones and more and more computers).
  • Assembly gives readable names to these instructions (ADD, MOV, JMP), one for one. This is what you imitated with LOAD and ADD.
  • High-level languages (Python, Java, C, JavaScript…) are expressed with variables, functions and loops. A single one of their lines often becomes dozens of machine instructions.

Compile or interpret

There are two main ways to run a high-level program:

  • compile: a compiler translates the whole program into machine code, before it runs. You get an executable file, fast, but specific to one type of processor and system. This is the case for C, C++, Rust or Go;
  • interpret: an interpreter reads the program and executes it as it goes, like the machine of the previous chapter. It is more flexible, but often slower.

In practice, many languages mix the two. Python first compiles your file into bytecode, simple instructions for a virtual machine, then a virtual machine interprets it. Java does the same with its own bytecode, and techniques such as just-in-time compilation (JIT) also translate the most used parts into machine code while the program runs.

It is itself a program compiled to machine code, which the processor executes.

Step 5 of 5
Text description of the animation
  1. You write Python that humans can read.
  2. Python parses the whole file. A syntax mistake stops it here, before anything runs.
  3. It produces bytecode: elementary instructions for its virtual machine.
  4. The virtual machine executes this bytecode instruction by instruction, like our simulator.
  5. It is itself a program compiled to machine code, which the processor executes.

See Python's bytecode

The dis module (disassembler) displays a function's bytecode:

import dis

def total(price, quantity):
    return price * quantity

dis.dis(total)
  3           RESUME                   0

  4           LOAD_FAST_LOAD_FAST      1 (price, quantity)
              BINARY_OP                5 (*)
              RETURN_VALUE

You can recognise the logic of our small machine: load price and quantity (LOAD_FAST_LOAD_FAST, which loads both at once), multiply them (BINARY_OP with the * operation), return the result (RETURN_VALUE). RESUME marks the start of the function for the virtual machine. The number on the left is the line number in the source code. These bytecode details change from one Python version to another: they help you understand, not program.

The operating system

Between your programs and the hardware sits the operating system (Windows, macOS, Linux, Android, iOS…). It:

  • shares the processor between programs, switching from one to another hundreds of times per second;
  • gives each program its own memory area, and stops it from reading the others';
  • manages files, the network, the screen, the keyboard: when your program writes a file, it asks the system to.

It is also what starts a program: it loads it from storage into RAM, then asks the processor to execute its first instruction.

Mini-lab: look under the bonnetPython 3.13

Output

Click “Run”: Python will load in your browser (about 10 MB the first time).

Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor

Your turn

Worked exercise

Worked exercise: a syntax checker

Write a function check(code) that returns "OK" if the text code is syntactically correct Python, and otherwise the error message with its line number, without running the code. Test it on "x = 1 + 2", on "print('a'" and on "for i in range(3)\n print(i)".

Hint 1
The built-in function compile(code, "<exercise>", "exec") compiles without running.
Hint 2
A SyntaxError caught with except SyntaxError as e provides e.msg and e.lineno.
Show the solution and common mistakes
def check(code):
    try:
        compile(code, "<exercise>", "exec")
        return "OK"
    except SyntaxError as e:
        return f"line {e.lineno}: {e.msg}"

print(check("x = 1 + 2"))
print(check("print('a'"))
print(check("for i in range(3)\n    print(i)"))
OK
line 1: '(' was never closed
line 1: expected ':'

compile does exactly Python's first step: parsing and translation to bytecode. Code editors do the same kind of check to underline your mistakes as you type.

Common mistakes:

  • Using exec(code) to test: the code would be executed, with all its effects. If the text comes from a user, it is even a serious security hole.
  • Catching every exception with except Exception: syntax errors would be mixed up with other problems, and the message would lose its meaning.

Summary

  1. 1Machine code is the processor's language; assembly makes it readable; high-level languages move away from it.
  2. 2A compiler translates the whole program before running; an interpreter executes it as it goes.
  3. 3Python compiles your file into bytecode, then its virtual machine executes it; dis lets you see it.
  4. 4A syntax error stops the whole file from starting; other errors happen while running.
  5. 5The operating system shares the processor and memory between programs, and manages files and devices.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.