Foundations · about 25 min

What a program is

Why this matters

Everything a computer does, from showing this page to routing your network traffic, happens because someone wrote down precise instructions and a machine followed them. Before learning any syntax, it pays to have a clear picture of what a program actually is, who reads it, and what "running" it means. That picture will make every later topic (variables, functions, errors) easier, because you will know where the code lives and what is acting on it.

Instructions, precisely

A program is a list of instructions written so precisely that a machine can carry them out with no judgment of its own. Humans tolerate vagueness ("make some tea"); computers cannot. A program has to say exactly what to do, in what order, with which data.

Think of a recipe written for someone who follows it literally:

1. Fill the kettle with 500 ml of water.
2. Switch the kettle on.
3. Wait until the water boils.
4. Put one tea bag in the cup.
5. Pour the water into the cup.

Three ideas are already here, and they appear in every programming language:

What the machine actually understands

The processor (CPU) in your computer understands only machine code: binary-encoded instructions such as "add these two numbers held in registers" or "copy 8 bytes from this memory address". Each CPU family (x86-64, ARM) has its own instruction set. Writing machine code by hand is possible but slow and error-prone, and the result works on one kind of CPU only.

So people invented high-level languages like Python. You write source code: plain text that humans can read, using words like print, if and for. Some other program must then turn that text into something the CPU can act on. There are two broad strategies:

StrategyHow it worksExamples
Compile ahead of timeA compiler translates the whole source into a machine-code file once; you run that fileC, Rust, Go
InterpretAn interpreter program reads your source and carries out its instructions each time you run itPython, Bash, Ruby

Python is in the second group. The program called python3 on your system is the interpreter. It is itself machine code (the standard implementation, CPython, is written in C). When you run a Python program, the picture is:

   your file: hello.py   (text)
          |
          v
   python3  (the interpreter, a machine-code program)
          |   reads the text, understands it, does what it says
          v
   CPU executes the interpreter's machine code
          |
          v
   effects: text on the screen, files written, network packets...

The CPU never sees your Python text directly. It runs the interpreter, and the interpreter runs your program. The next lesson looks inside that middle box and shows that Python actually compiles your source to an intermediate form called bytecode first.

Your first program

Here is a complete Python program:

print("Hello, world!")

Save it in a file named hello.py and run it from a terminal:

$ python3 hello.py
Hello, world!

Let us take apart the one line:

A program with several lines runs them in order:

print("Fill the kettle")
print("Switch it on")
print("Wait for the boil")

Output:

Fill the kettle
Switch it on
Wait for the boil

print can also show numbers, and Python can compute them first:

print(2 + 3)
print("2 + 3")

Output:

5
2 + 3

Notice the difference. 2 + 3 without quotes is an expression that Python evaluates to the number 5. With quotes, "2 + 3" is just text, five characters long, printed exactly as written. Keeping "code" and "text that happens to look like code" apart is one of the first habits to build.

Programs have input, processing and output

Almost every program fits this shape:

  input  -->  processing  -->  output
 (data in)   (the instructions)  (results out)

Our hello program has no input and a fixed output. Soon you will read input typed by a user (lesson 4 of this module), then from files and command-line arguments. In the learnprog exercises, your program's output (what it prints) is compared with the expected output, so getting the exact text right, including spaces and capitalization, matters.

Common mistakes

Forgetting the quotes.

print(Hello)
Traceback (most recent call last):
  File "hello.py", line 1, in <module>
    print(Hello)
          ^^^^^
NameError: name 'Hello' is not defined

Without quotes, Python reads Hello as a name (something that should refer to a value) rather than as text. No such name exists, so you get a NameError. The message tells you the file, the line number, and points at the problem with ^^^^^. Reading these messages carefully is a skill; you will practice it all through the track.

Mismatched quotes or parentheses.

print("Hello, world!)
  File "hello.py", line 1
    print("Hello, world!)
          ^
SyntaxError: unterminated string literal (detected at line 1)

A SyntaxError means Python could not even understand the structure of your text, so nothing ran, not even the lines before the error. That is a clue about how Python works: it reads the whole file before running any of it. The next lesson explains why.

Capital letters. Python is case-sensitive: Print("hi") fails with NameError: name 'Print' is not defined. The function is print, all lowercase.

Recap

Going further: run python3 --version in a terminal to see which interpreter you have, and which python3 to see where that program lives on disk. It is just a file, like any other program.

Exercises

Exercise 1 · quiz

Who executes Python code?

Your CPU only understands machine instructions. When you run python3 hello.py, what actually reads and carries out the lines in hello.py?

Answer
  • The Python interpreter, itself a machine-code program, reads the source and carries out its instructions

The interpreter (python3) is an ordinary program compiled to machine code, usually written in C (that implementation is called CPython). It reads your source text, translates it to an internal form, and performs the work your program describes. The CPU runs the interpreter; the interpreter runs your program.

Exercise 2 · write code

Your first program

Write a program that prints exactly these two lines:

Hello, world!
I am learning Python.

File: main.py

Starting point

# Replace this comment with two print() calls.

Example

expected output

Hello, world!
I am learning Python.
Hint 1

Each call to print(...) writes one line.

Hint 2

Put the text in quotes: print("Hello, world!").

Reference solution
print("Hello, world!")
print("I am learning Python.")

Exercise 3 · quiz

Sequence

What does this program print? Type the output exactly as one line, with the numbers separated by single spaces (for example 1 2 3).

print(3)
print(1)
print(2)
Answer

A program is a sequence of instructions carried out top to bottom, one after another. Python does not sort, reorder or skip statements unless you tell it to (with the control flow you will meet in a later module).

Exercise 4 · write code

A tiny recipe

Write a program that prints a three-step recipe, numbered exactly like this:

Step 1: Boil water
Step 2: Add tea
Step 3: Wait 3 minutes

File: main.py

Starting point

print("Step 1: Boil water")

Example

expected output

Step 1: Boil water
Step 2: Add tea
Step 3: Wait 3 minutes
Hint 1

You need one print per line of output.

Hint 2

Check capitalization and the colon after each step number.

Reference solution
print("Step 1: Boil water")
print("Step 2: Add tea")
print("Step 3: Wait 3 minutes")