How Python Variables Work: Reassign, Swap and More
Changing a Variable's Value
A variable can change. Assign a new value, and it replaces the old one:
language = "Java"
language = "Python"
print(language)Python
This is called reassignment. The old value, "Java", is gone. A variable holds only one value at a time, and it keeps no history.
Think of a whiteboard: when you write a new value, you wipe the old one first.
Change it using its own value
You can even calculate a new value from the old one:
score = 10
score = score + 5
print(score)15
This line looks strange in maths, but in Python it makes sense. Read it as "score gets score plus 5":
- Python works out the right side first:
10 + 5is15. - Then it stores
15back inscore.
This is how games add points, shops update stock, and counters count. You'll see a shorter way to write it in the Data Types chapter.
Order still matters
Python runs top to bottom, so a print() shows the value at that moment:
lives = 3
print(lives)
lives = 2
print(lives)3 2
Assign a new value, and the old one is replaced. A variable remembers only its latest value.