Variables — Pseudocode

If the computer runs price ← 4000, then price ← 5000, what does price hold now? Both numbers, or only one? Guess first, the answer is in the second section…

If the computer runs price ← 4000, then price ← 5000, what does price hold now? Both numbers, or only one? Guess first, the answer is in the second section.

That small question holds nearly everything you need to know about variables. The rest is one thing that often confuses new programmers: why swapping what two names hold needs a third name.

← stores a value in a name

price ← 5000
PRINT price
PRINT "price"
5000
price

A variable name may hold letters, digits and underscores, and must start with a letter. No spaces, so write icedTeaPrice or iced_tea_price. In JavaScript later, that line becomes let price = 5000. In Python, price = 5000.

One name, one value

price ← 4000
price ← 5000
PRINT price
5000

That answers the question at the top. A variable holds only one value. When price ← 5000 runs, 4000 is thrown away and replaced by 5000. No history is kept.

A name can also be used to work out its own new value:

stock ← 12
stock ← stock - 3
PRINT stock
9

In maths, stock = stock - 3 makes no sense. Here it's an instruction, not an equation. The computer works out the right side first with the old value (12 - 3), and only then stores the result, 9, in stock.

Copying the value, not linking the names

price ← 5000
oldPrice ← price
price ← 6000
PRINT oldPrice, price
5000 6000

oldPrice ← price copies what price holds at that moment, 5000, into oldPrice. After that the two have nothing to do with each other. When price changes to 6000, oldPrice stays 5000.

Swapping two variables

You have two glasses: glass A holds tea, glass B holds coffee. How do you swap what's in them? You need a third, empty glass. Guess first what gets printed when there's no third glass:

glassA ← "tea"
glassB ← "coffee"
glassA ← glassB
glassB ← glassA
PRINT glassA, glassB
coffee coffee

The third line pours the coffee into glass A, and the tea is gone right then. The fourth line only copies that coffee back into glass B. Keep what glass A holds somewhere else first:

glassA ← "tea"
glassB ← "coffee"
temp ← glassA
glassA ← glassB
glassB ← temp
PRINT glassA, glassB
coffee tea

temp holds the tea while glass A is filled with coffee, then hands it to glass B. Three lines, and their order matters.

⚠️ Names the computer doesn't recognise

TL;DR: price ← 5000 stores 5000 in the variable price (<- and = work too). A variable holds only one value: a new value throws the old one away. stock ← stock - 3 works out the right side first with the old value, then stores the result. a ← b copies what b holds at that moment, it doesn't link the two. Swapping two variables needs a third one: temp ← a, a ← b, b ← temp. Names have no spaces, start with a letter, and capitals count.

What you will learn