Variables
Why we need variables
Analogy
- You are working out a bill:
248 * 3 + 248 * 3 * 0.18. It works. - Then the price changes to 310. Now you have to hunt down every
248and fix it, and if you miss one the bill is quietly wrong and nothing warns you. - So instead you give the number a name, once, and use the name from then on.
- Change it in one place and the whole thing updates. As a bonus, the code now reads like English.
price = 248quantity = 3 subtotal = price * quantitytax = subtotal * 0.18total = subtotal + taxWhat is a variable?
Definition
A variable is a name attached to a place in memory.
Memory is a huge wall of numbered slots. Your value sits in one of them, and nobody wants to remember "the value in slot 4,299,318,110" - so you stick a label on it that says price and use the label from then on.
That is the entire idea.
The equals sign is lying to you
This is the biggest hurdle for every beginner, so it is worth reading twice.
= does not mean "is equal to". It means: take the value on the right, and put it into the thing on the left. It is an instruction, not a statement of fact. Read it as "gets" or "becomes".
Which is why this line, which is nonsense in maths, is completely ordinary in code:
count = count + 1Read it as: take the current value of count, add 1, store the result back into count. If count was 5, it is now 6.
When you actually want to ask whether two things match, that is ==. Two different jobs, two different symbols, and mixing them up is the classic first bug.
Declare, initialise, assign
Three ideas that Python squashes into one line and C makes you do separately.
| Word | Means | Example |
|---|---|---|
| Declare | Announce that the name exists | int score; |
| Initialise | Give it its first value | score = 0; |
| Assign | Change the value later | score = 10; |
Using a variable that was declared but never given a value is a real bug. Some languages catch it. Others hand you whatever rubbish was already sitting in that memory slot.
Naming
The language enforces the rules. Other humans enforce the conventions, and the conventions matter more than they sound.
Rules: letters, digits and underscores only. Cannot start with a digit. No spaces. Case matters, so score and Score are two different variables. Cannot use reserved words like if or return.
Conventions: say what it holds. n tells nobody anything and numberOfStudents tells them everything. Python uses snake_case, Java and JavaScript use camelCase. Booleans read well as questions, like is_valid. Short names are fine for loop counters and nowhere else.
Note
You will spend far more time reading code than writing it, including your own from three months ago. Good names are the cheapest gift you can give your future self.
Scope and lifetime
A variable does not exist everywhere in your program. It exists inside the region where it was created, and that region is its scope.
def calculate(): result = 100 # exists only inside this function return result print(result) # error, nothing called result out hereThink of scope as a room. What is inside is private to it, and when you leave, those things are gone.
Scope is about where a variable can be seen. Lifetime is about how long it exists. A local variable is born when the function starts and dies when it ends, so calling the function again gives you a brand new one with no memory of last time.
def counter(): count = 0 count = count + 1 return count counter() # 1counter() # 1 again, not 2That surprises people, and it is the whole point: every call gets a fresh, clean workspace.
Watch out
Global variables live outside everything and can be reached from anywhere. They sound convenient and are usually a trap: if any part of the program can change a value, then when it holds something wrong you have to search the entire program to find out who did it. Keep every variable in the smallest room that works.
Two names, one value
Here is the moment that catches almost everybody.
For simple values, the variable holds the value itself, so b = a makes a genuine copy and the two go their separate ways.
For bigger things like lists and objects, the variable holds the address of the value. So y = x copies the address, not the contents, and both names end up pointing at the same box.
Note
You do not need to absorb this fully yet. The memory chapter takes it apart properly, once you have the vocabulary for it. For now it is enough to remember that copying a list is not as simple as copying a number.
Constants
Some values should never change: pi, the number of days in a week, a tax rate. Marking them as constants tells the language to reject any attempt to change them, and tells other programmers the value is fixed.
Java writes final, JavaScript writes const. Python has no real constants, so the convention is to write the name in capitals - a message to other humans rather than a rule the language enforces.
Mistakes to watch for
Watch out
- Using
=when you meant==. In C and Java,if (x = 5)assigns instead of comparing, and is then always true. - Using a variable before giving it a value.
- Expecting the name to update itself.
total = price * 2calculates once. Changepriceafterwards andtotaldoes not move. - Typos in names.
totlandtotalare two separate variables, and in a dynamic language nobody warns you. - Assuming a variable declared inside an
ifor a loop is visible outside it. In most languages it is not.
Quick recap
- A variable is a name attached to a place in memory
=puts a value in. It does not mean "is equal to"- Declare, initialise, assign are three separate ideas
- Scope is where it can be seen, lifetime is how long it lives
- Keep every variable in the smallest scope that works
- Copying a number copies the value. Copying a list copies the address
Key takeaway
A variable is a name for a value, and the equals sign is the act of putting the value there.