Variables are so fundamental to programming that it is easy for an experienced programmer to forget what it means to learn about them for the first time.

An easy one

This program is easy for a beginner who has learned that * is multiplication:

x = 15
write x * x

Clearly the first line says x stands for 15, so the second line writes 15 * 15, which is 225.

A hard one

On the other hand, a typical beginner cannot predict that this program writes only perfect squares, (even after they have learned that random [1..10] makes a random number from 1 to 10).

x = random [1..10]
write x * x

What is the trick here?

Definitions versus memory

In code, the assignment x = value represents storing a value in memory.

But if you have never written a program before, your experience is that variables are used for definitions, not memory. When variables are used in algebra, the statement x = y + 1 represents a permanent timeless definition. Therefore you might read our program like this:

  1. Define x to mean random [1..10] everywhere. (wrong)
  2. Now write x * x means write (random [1..10]) * (random [1..10]).
  3. So it might randomly write something like 3×7 = 21. (nope)

This is the wrong mental model in most modern programming languages. Here is the way to think about it:

  1. Calculate random [1..10] and store the answer in memory as x. (right)
  2. Now write x * x means to look up the stored value of x each time it is needed.
  3. So it might randomly write something like 8×8 = 64. (yes!)

Variables are different in code and algebra. Variables in code represent a piece of memory.

Key concepts

  • A variable is name for a piece of memory.
  • A program is run in order from top to bottom.
  • Assignments x = value store a value in memory.
  • Referring to a variable looks up the value in memory.