Grade 7 Computer Science · Values and names

A variable is a name, not a box

The name stays; the value it points at can be replaced entirely.

A line any math teacher would cross out

In a math class, x = x + 1 is simply false: no number equals itself plus one. In a program it is one of the most common lines there is, and it works perfectly. What changed — the mathematics, or what the = sign says?

In the first unit we saw that the computer executes exactly what is written. Now we give it something to remember. The idea is simple, and nearly every beginner pictures it slightly wrongly — so it is worth getting right at once.

An assignment ties a name to a value — and it can be tied again.
x = 5
x = x + 1
print(x)
What is writtenA mathematical readingA programming reading
A name equals a valueA statement that can be checkedA command that ties
A name equals itself plus oneA false statementA valid command

Why “a box” is a misleading picture

Many books draw a variable as a box with the value sitting inside it. The picture helps at first and hinders later: it makes one think there is one box whose contents change, and so it becomes hard to explain what happens when two names point at the same value. The more accurate picture is a label: the name is a tag that can be stuck on a value, and two different tags can be stuck on exactly the same value. In the unit on lists that will become very important.

Example 1 — reading an assignment as a command

  1. One sees the line x = x + 1.
  2. Read the right side first: the value of x, plus one.
  3. The result is a new value.
  4. The command ties the name x to the new value.

Example 2 — why the reading order matters

  1. The right side is computed in full first.
  2. Only afterwards does the tying happen.
  3. So the old value is available during the computation.
  4. And without that rule x = x + 1 would be meaningless.
An assignment is a command: compute the right, and only then tie the name on the left.