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.
x = 5
x = x + 1
print(x)| What is written | A mathematical reading | A programming reading |
|---|---|---|
| A name equals a value | A statement that can be checked | A command that ties |
| A name equals itself plus one | A false statement | A 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
- One sees the line
x = x + 1. - Read the right side first: the value of x, plus one.
- The result is a new value.
- The command ties the name x to the new value.
Example 2 — why the reading order matters
- The right side is computed in full first.
- Only afterwards does the tying happen.
- So the old value is available during the computation.
- And without that rule
x = x + 1would be meaningless.