Chapter 08

Introduction to Programming

Middle School
At a glance
Core ideaA program has state that changes step by step over time.
Key termVariable — a named box holding a value that can change.
You can…Trace how each line reads and updates the program's state.
Watch out= is assignment, not equality — count = count + 1 is fine.
Theory

A program is a precise sequence of instructions that transforms input into output. Programming languages give us abstractions above raw bits: a variable is a named box holding a value; a type classifies what a value is and what may be done to it; an expression computes a value; and a statement performs an action, often changing the program's state (the current contents of all variables).

Core primitive types include integers, floats (reals), booleans (True/False), and strings (text). Assignment x = 5 binds a name to a value. Operators combine values: arithmetic (+ - * / % **), comparison (== != < >), and logical (and or not). Evaluation follows precedence rules, just like mathematics.

Explanation

The single most important mental model for a beginner is that a program has state that changes over time. Reading code is not like reading a static equation; it is like watching a machine step forward, mutating its memory at each line. The value of x depends on when you look.

A subtle but vital point: = in programming is assignment, not mathematical equality. The line count = count + 1 is nonsense as an equation but perfectly sensible as an instruction: "take the current value of count, add one, store it back." Confusing these two meanings is the root of many beginner bugs.

Discipline. Computers are ruthlessly literal. They do exactly what you wrote, not what you meant. Debugging is the art of finding the gap between the two — and that gap is always your own instruction, never the machine's whim.

Practical

A classic first real program: convert a temperature from Celsius to Fahrenheit, then classify it. We trace state as it evolves.

# A program is input -> transformation -> output.

def celsius_to_fahrenheit(c):
    return c * 9 / 5 + 32          # arithmetic expression, precedence: * / before +

def describe(celsius):
    f = celsius_to_fahrenheit(celsius)     # state: f now holds a float
    # Booleans and comparison produce True/False:
    freezing = celsius <= 0
    boiling  = celsius >= 100
    if freezing:
        label = "freezing"
    elif boiling:
        label = "boiling"
    else:
        label = "liquid"
    return f, label

for c in [-10, 25, 100]:
    fahrenheit, state = describe(c)
    print(str(c) + "C = " + str(fahrenheit) + "F  (" + state + ")")

# Output:
# -10C = 14.0F  (freezing)
# 25C = 77.0F   (liquid)
# 100C = 212.0F (boiling)

Trace it: describe(25) sets f = 77.0, evaluates freezing = False and boiling = False, so the else branch sets label = "liquid". Each line reads the current state and may update it — the essence of imperative programming.

Q&A
Q1 What is the difference between a statement and an expression?

An expression evaluates to a value (3 + 4 becomes 7). A statement performs an action and may not produce a value (x = 7 stores something; if ...: directs flow). Expressions are the nouns of a language; statements are the verbs. Many statements contain expressions.

Q2 Why does 5 / 2 give 2.5 but 5 // 2 give 2?

/ is true division and yields a float. // is floor (integer) division, discarding the fractional part. The companion operator % (modulo) gives the remainder, so 5 // 2 == 2 and 5 % 2 == 1, and together they satisfy 2*2 + 1 == 5.

Q3 What is a "type error" and why do types exist at all?

A type error occurs when you apply an operation to a value it does not support — e.g. adding a number to a list. Types exist to catch nonsense early and to tell operators how to behave: "3" + "4" concatenates to "34", while 3 + 4 adds to 7. The same symbol means different things depending on the operands' types.

Q4 Why is count = count + 1 valid if it is false as an equation?

Because = is assignment, evaluated right-to-left: first compute the right side using the old value of count, then rebind the name to the result. It is a command ("increment count"), not an assertion of equality. This is why languages like it exist alongside pure mathematics — they describe processes, not timeless truths.

Concept mind map

How the ideas connect

Every key idea in this chapter, branching from the core concept — use it to see the whole picture at a glance.

variablevaluestateassignmentread then updateruns line by lineIntro to programming
Infographic

The key facts, visualised

Variable
A named box that holds a value which can change over time.
Assignment
x = x + 1 means compute the right side, then store it in x.
State
The set of all variable values at one moment in the program.
Sequence
Lines run top to bottom, each changing the state.
Solved examples

Worked problems, step by step

Follow each solution line by line, then try to reproduce it on paper before moving on.

Example 1Trace: x = 5; x = x + 3; x = x * 2. Final x?

  1. x becomes 5.
  2. x = 5 + 3 = 8.
  3. x = 8 * 2 = 16.

Example 2Swap two variables a=1, b=2 using a temp t.

  1. t = a (t=1).
  2. a = b (a=2).
  3. b = t (b=1).
Practice problem set

Now you try

Work each one out first, then tap to reveal the worked answer.

1What is a variable?
A named box that holds a value; the value can change as the program runs.
2What does x = x + 1 do?
It reads the current value of x, adds 1, and stores the result back into x.
3What is program state?
The collection of all current variable values at a given point in time.
4Trace y = 2; y = y + y. What is y?
y starts at 2, then y = 2 + 2 = 4.
5Why do we need a temp variable to swap two values?
Overwriting one first would lose its old value, so a temp holds it until the swap is done.
6In what order do plain program lines run?
Top to bottom, one after another, each line updating the state.