BasicsChapter 5 of 114
Variables
Names that point at values, and what assignment really does.
Assignment
A variable is a name pointing at a value. You make one by assigning to it. There is no keyword and no type declaration:
name = "Ada"
age = 36
print(name, age)Output
Ada 36
Read = as "refers to", not "equals". The name on the left starts pointing at the value on the right.
Names are labels, not boxes
A useful picture: the value sits in memory, and the name is a label tied to it. Assigning again moves the label; it does not change the old value.
a = "first"
b = a
a = "second"
print(a)
print(b)Output
second first
b still points at the original string. Only a was re-pointed.
The type comes from the value
A variable has no type of its own. Whatever you put in it decides that, and you can put something else in later:
thing = 42
print(type(thing))
thing = "now a string"
print(type(thing))Output
<class 'int'> <class 'str'>
This is what "dynamically typed" means. It is flexible, and it is also why a typo in a name is not caught until that line runs.
Assigning is not comparing
One = assigns. Two == compares, and gives back True or False:
score = 10
print(score == 10)
print(score == 11)Output
True False
Updating a variable
To change a value based on what it already holds, read it and assign the result back:
total = 100
total = total + 15
print(total)Output
115
That pattern is common enough to have a shorthand:
total = 100
total += 15
total -= 5
total *= 2
print(total)Output
220
Deleting a name
del removes the name. The value goes too, once nothing points at it:
temp = "scratch"
print(temp)
del temp
print("the name is gone")Output
scratch the name is gone
Test yourself
2 questionsAfter a = "first"; b = a; a = "second", what is b?
Show the answer
"first" — Assigning to a moved that one label. b still points at the original string.
What does = do?
Show the answer
Points the name on the left at the value on the right — Comparing is ==. Reading = as 'refers to' avoids a lot of confusion later.
Variable Names
What Python allows, what it forbids, and what other people expect.