Variables
What a variable really is, why = is a bit of a liar, and how to name things that will outlive your motivation. For complete beginners, with a bleak sense of humour.
By the end of this tutorial you will know:
- what a variable actually is (not what most tutorials claim)
- how to name one
- the five types you will meet first
- why changing one thing sometimes changes another
- where variables live, and how they die
Prerequisites: Python 3 installed. Check with python3 --version in a terminal. Nothing else. Not even hope.
How this was checked: every example was run on Python 3.11, 3.12 and 3.13, and the output shown is the real output, identical on all three. Where an example crashes on purpose, we show only the last line of the error, because that is the line that matters.
To follow along: save an example as a .py file and run it with python3 yourfile.py, or type it into the interactive prompt (start it with python3, leave it with exit()).
1. A variable is a name tag, not a box
Most tutorials tell you a variable is a box that holds a value. This is a comforting lie, like "the fire alarm is just a test".
A variable holds nothing. A variable is a name that you attach to a value, like a toe tag, but for data. The value already exists somewhere in the computer's memory. The name just lets you point at it.
answer = 42
print(answer)
print(type(answer))42
<class 'int'>Read answer = 42 as "the name answer now refers to the number 42". The = here does not mean "equals" like in maths. It means "attach this name to that thing". The name goes on the left, the thing goes on the right, and Python does the rest.
print(answer) shows the value. type(answer) asks what kind of thing it is. Here, an int: a whole number.
Hold on to the name tag idea. It sounds like a minor detail, and it is in fact the entire foundation. Everything weird that happens later in this tutorial makes sense once you stop thinking of boxes.
2. Creating and changing variables
You create a variable the moment you assign to it. No ceremony, no paperwork, no declaration. Python is the most trusting bureaucracy you will ever deal with.
mood = "optimistic"
print(mood)
mood = "Monday"
print(mood)optimistic
MondayThe second assignment moves the name tag from "optimistic" to "Monday". The old value was not hurt. It was simply forgotten, which in a computer is the same thing as dead, but quieter.
Order matters. Python reads your file from top to bottom, one line at a time. A name does not exist until the line that creates it has run:
print(coffee)
coffee = "empty"NameError: name 'coffee' is not definedNameError means "you used a name I have never heard of". Here you tried to drink the coffee before you made the coffee. The fix is to swap the two lines, which is also the fix for most mornings.
Make a variable called mood, print it, change it to something worse, and print it again. Then put a print(mood) at the very top of the file and read the error. Learning to read errors calmly is most of programming.
3. Naming things
There is an old joke that the hardest problems in programming are cache invalidation, naming things, and off-by-one errors. Naming is the one you can start getting right today.
Python has a few firm rules for names:
- Letters, digits and underscores only.
- It cannot start with a digit.
- It is case-sensitive:
Doomanddoomare two different names. - It cannot be a keyword, a word Python has reserved for itself.
Case-sensitivity first, because it will ruin an afternoon at some point:
Doom = 1
doom = 2
print(Doom, doom)1 2Two names, two values, zero warnings. Python will not tell you that you meant the same one. This is the programming equivalent of two people named Gerald in the same office.
To check whether a word is reserved, ask Python itself:
import keyword
print(keyword.iskeyword("class"))
print(keyword.iskeyword("coffee"))True
Falseclass is taken. coffee is available, and sadly so is your coffee.
Breaking the rules gets you a SyntaxError, which means Python could not even read the line, let alone run it:
2nd_place = "first loser"SyntaxError: invalid decimal literalmy-variable = 3SyntaxError: cannot assign to expression here. Maybe you meant '==' instead of '='?class = "Gerald"SyntaxError: invalid syntaxThe second one is Python reading my-variable as "my minus variable", which is not something you can attach a name to. The wording of syntax errors changes between Python versions, so do not be alarmed if yours reads slightly differently. The line is still wrong.
What to do instead: Python programmers write names in snake_case: lowercase words joined by underscores, like days_left or bank_balance. Make the name say what the thing is. days_left tells a story. d tells nobody anything.
Name your variables for the person who will read your code in six months. That person is you. You will not remember writing it, and you will be angry.
4. The five types you will meet first
Every value has a type, which says what kind of thing it is and what you can do with it. Five cover most of your first year:
| Type | What it is | Example |
|---|---|---|
int | whole number | 12 |
float | number with a decimal point | -3.5 |
str | text, in quotes | "Gerald" |
bool | True or False | True |
NoneType | the deliberate absence of a value | None |
days_left = 12
bank_balance = -3.50
name = "Gerald"
is_alive = True
nothing = None
for value in (days_left, bank_balance, name, is_alive, nothing):
print(value, type(value))12 <class 'int'>
-3.5 <class 'float'>
Gerald <class 'str'>
True <class 'bool'>
None <class 'NoneType'>(The for loop is just a way to do the same thing to each item. You will meet it properly later. For now, trust it, which you should never do again.)
None is Python's way of saying "there is nothing here, and that is on purpose". It is not zero. It is not an empty string. It is the void, with a name.
Names have no type. Values do.
Here is where the name tag idea pays off. The name thing has no type. The value it points at does. So you can move the tag to a different kind of thing:
thing = 7
print(type(thing))
thing = "seven"
print(type(thing))<class 'int'>
<class 'str'>Python is fine with this. It does not care what you attach to a name, which is both its greatest strength and the source of roughly half of all bugs.
Two things about numbers that will surprise you
Decimal numbers are slightly wrong. Not Python's fault: computers store them in binary, and a number like 0.1 cannot be stored exactly, in the same way that one third cannot be written exactly as a decimal.
print(0.1 + 0.2)
print(0.1 + 0.2 == 0.3)
print(round(0.1 + 0.2, 2) == 0.3)0.30000000000000004
False
TrueDo not compare floats with == and expect justice. Round them first, or compare with a tolerance. (Here == asks "are these equal?", and the answer was no, because of that tiny leftover.)
And two fun facts in one example. Whole numbers do not overflow the way they do in some languages, and True secretly behaves like 1:
print(2 ** 100)
print(True + True)1267650600228229401496703205376
2** is "to the power of". Python happily gave you a 31-digit number. And True + True is 2, because a bool is a kind of number wearing a costume.
5. Strings and conversions
Joining text together is called concatenation, and you do it with +. An easier way is the f-string: put an f before the opening quote and write variable names inside curly braces.
name = "Gerald"
days_left = 12
greeting = "Hello, " + name + "."
print(greeting)
print(f"{name} has {days_left} days left.")Hello, Gerald.
Gerald has 12 days left.Use f-strings. They are shorter, they read like sentences, and they never make you wonder where the spaces went.
Python will not guess what you meant
Try to glue text and a number together with + and Python refuses:
age = 30
print("Age: " + age)TypeError: can only concatenate str (not "int") to strTypeError means "this operation does not work on this kind of thing". Python will not quietly turn the 30 into text for you. It is a language of firm boundaries, a bit like a bouncer. You fix it by converting on purpose, or by using an f-string, which converts for you:
age = 30
print("Age: " + str(age))
print(f"Age: {age}")Age: 30
Age: 30Conversion goes both ways. int("42") turns text into a whole number and float("3.5") turns text into a decimal. But the text has to actually look like a number:
print(int("42") + 1)
print(float("3.5"))
print(int("forty-two"))43
3.5
ValueError: invalid literal for int() with base 10: 'forty-two'The first two lines worked. The third raised a ValueError: right kind of thing (text), wrong contents. Python cannot read the word "forty-two" as a number, and neither can most users' input forms.
You should now be able to predict every output above before you run it. If you can't, reread the section on the name tag. It will still be there, unlike your free time.
6. Mutable and immutable: the part that bites
Some values can be changed after they are made. These are mutable. Others can never be changed, only replaced. These are immutable. Numbers, True/False, None and strings are immutable. Lists (which you will meet properly in a later tutorial) are mutable.
Strings first. You cannot edit one in place:
word = "doom"
word[0] = "b"TypeError: 'str' object does not support item assignmentYou can only make a new string. String methods like .upper() do exactly that, and give you the new value back:
word = "doom"
loud = word.upper()
print(word)
print(loud)
word = word.upper()
print(word)doom
DOOM
DOOMThe original "doom" was never touched. .upper() made a brand new string, and word = word.upper() moved the tag onto it. (The old one is still dead.)
Two tags on one thing
Now the payoff for the name tag idea. A list is an ordered collection in square brackets. Watch what happens when two names point at the same list:
a = [1, 2, 3]
b = a
print(a is b)
b.append(4)
print(a)True
[1, 2, 3, 4]b = a did not copy the list. It put a second tag on the same list. So a is b is True (is asks "are these the very same object?"), and when we added a 4 through b, a saw it too. They are the same list.
If you thought of variables as boxes, this result makes no sense: how did a number appear in a box you never touched? With tags, it is obvious. There is one list and two tags. Change the list through either tag and both tags see it.
To get a separate list, make a copy:
a = [1, 2, 3]
b = a.copy()
b.append(4)
print(a, b)
print(a == b, a is b)
c = [1, 2, 3, 4]
print(b == c, b is c)[1, 2, 3] [1, 2, 3, 4]
False False
True FalseNow a and b are two lists, and changing one leaves the other alone. And look at the last line: b == c is True (same contents) while b is c is False (different objects). That is the difference between the two:
==asks: do these look the same?isasks: are these the same thing?
Two people can have the same name without being the same person. Usually. Probably.
Rebinding versus mutating
One more trap, and it is a good one. += behaves differently depending on whether the value is mutable:
x = 10
y = x
x += 1
print(x, y)
pals = ["Gerald"]
others = pals
pals += ["Brenda"]
print(pals, others)11 10
['Gerald', 'Brenda'] ['Gerald', 'Brenda']Numbers cannot change, so x += 1 makes a new number and moves the x tag to it. y stays on the old 10. A list can change, so pals += ["Brenda"] changes the list itself, and others, tagged to the same list, sees Brenda too. Brenda did not ask to be in others.
With immutable values (numbers, strings, True/False, None), a "change" always means moving the tag to a new value. Other names are unaffected.
With mutable values (lists), a change alters the thing itself, and every name pointing at it sees the change. If you want an independent copy, ask for one with .copy().
7. Scope: where variables live
A variable made inside a function belongs to that function and disappears when it ends. This is scope: the region of code where a name exists. A function can read a name from outside:
doom_level = 1
def report():
print("doom level:", doom_level)
report()doom level: 1(def defines a function: a named, reusable chunk of code. Another tutorial will do it justice.) But assigning inside a function does not change the outside name. It creates a new, separate one that happens to share the name:
doom_level = 1
def escalate():
doom_level = 2
print("inside:", doom_level)
escalate()
print("outside:", doom_level)inside: 2
outside: 1Two different variables, both called doom_level, living in different places. The outside one never found out. And if you try to update the outside name from inside, Python gets suspicious:
doom_level = 1
def escalate():
doom_level += 1
escalate()UnboundLocalError: cannot access local variable 'doom_level' where it is not associated with a valueBecause the function assigns to doom_level, Python decides it is a local name inside that whole function. Then += 1 tries to read it before it has a value. The cleanest fix is to pass the value in and return the result, so the function does not secretly depend on the outside world:
doom_level = 1
def escalate(level):
return level + 1
doom_level = escalate(doom_level)
print(doom_level)2There is also a global keyword that lets a function change an outside name:
doom_level = 1
def escalate():
global doom_level
doom_level += 1
escalate()
print(doom_level)2It works. It is also how code becomes impossible to follow, because now any function anywhere might be quietly raising the doom level. Passing values in and returning results is almost always better. Use global the way you use a fire exit: knowing it exists, hoping never to.
8. Deleting a variable
del removes a name:
secret = "hunter2"
del secret
print(secret)NameError: name 'secret' is not definedThe name is gone, as if it never existed. Note what del removes: the tag, not necessarily the thing. If another name points at the same value, the value lives on:
a = ["evidence"]
b = a
del a
print(b)['evidence']You can destroy a all you like. As long as b exists, so does the evidence.
9. Constants, and other polite fictions
Python has no true constants. By convention, a name written in UPPER_CASE means "please do not change this", and nothing enforces it:
MAX_RETRIES = 3
MAX_RETRIES = 4
print(MAX_RETRIES)4Python let us change it without complaint. The capital letters are a request, not a lock. Whether your teammates tolerate it is a separate matter.
Two last conveniences. You can assign several names at once, and you can swap two values without a helper variable:
a, b = 1, 2
a, b = b, a
print(a, b)
x = y = 0
print(x, y)2 1
0 010. Common errors, at a glance
| Error | What it usually means | Fix |
|---|---|---|
NameError | You used a name before creating it, mistyped it, or deleted it | Check the spelling and the order of lines |
TypeError: can only concatenate str... | You used + on text and a number | Convert with str(), or use an f-string |
ValueError: invalid literal for int() | The text does not look like a number | Check what you are converting |
TypeError: 'str' object does not support item assignment | You tried to edit a string in place | Make a new string |
UnboundLocalError | A function assigns to a name and also reads it first | Pass the value in and return the result |
SyntaxError on a name | The name breaks a naming rule | Letters, digits, underscores, no leading digit, not a keyword |
| A list changed "by itself" | Two names point at one list | Use .copy() |
11. Practice
Predict the output before you run each one. Answers follow.
Exercise 1
a = "hope"
b = a
a = "despair"
print(b)Exercise 2
a = ["hope"]
b = a
a.append("despair")
print(b)Exercise 3. This script should print 120.0 but prints something else. Why?
total = 0
def add_tax(price):
total = price * 1.2
add_tax(100)
print(total)Answers
Exercise 1 prints hope. Strings are immutable, so a = "despair" moves the a tag to a new string. b still points at "hope". Hope survives, for now.
Exercise 2 prints ['hope', 'despair']. A list is mutable and both names point at the same one, so appending through a shows up through b. Hope and despair are now permanently in the same list.
Exercise 3 prints 0. The assignment inside add_tax creates a new local total, which vanishes when the function ends, and the outside total never changes. The fix is to return the value:
def add_tax(price):
return price * 1.2
total = add_tax(100)
print(total)120.0Capstone
Put it all together. Predict the output, then run it:
name = "Gerald"
days_left = 12
will_to_live = 0.4
print(f"{name}: {days_left} days left, {will_to_live * 100:.0f}% will to live.")
print(f"Type of will_to_live: {type(will_to_live).__name__}")Gerald: 12 days left, 40% will to live.
Type of will_to_live: float(:.0f inside the braces means "show this number with no decimal places". type(...).__name__ gives just the type's name, without the <class ...> wrapper.)
What you learned
- A variable is a name tag attached to a value, not a box that holds one.
=means "attach this name to that value", and the right side is worked out first.- Names are case-sensitive, follow a few rules, and read best in
snake_case. - Values have types (
int,float,str,bool,None). Names do not. - Python will not convert types for you. Use
str(),int(),float()or an f-string. - Immutable values are replaced; mutable ones (lists) are changed in place, and every name pointing at them sees it.
- Variables made in a function stay in that function. Return values instead of reaching outside.
Once variables feel boring, you are ready for decisions and loops: what if, for and while do with the things you have just learned to name. Go forth. Name responsibly.