Learning LibraryCore Coding LibraryTeens

Variables in Python: names bound to values

A variable is a name bound to a value. As your game runs, the score climbs and lives drop — variables are how a program remembers and updates that changing state.

The big idea

Assignment binds a name to a value; reassigning the name points it at a new value, which is how programs track state that changes over time.

See it in code

1The basics

Assignment binds a name to a value. Here score starts life bound to 0, and writing its name reads that value back:

python
score = 0
print("Score:", score)
Run it — the name now stands for its value:
Score: 0

One name, one value. Everywhere you write score, Python substitutes whatever it currently holds.

2A step further

Reassigning points a name at a new value — usually computed from the old one. Read score, add 40, then bind score to the result:

python
score = 0
score = score + 40
print("Score:", score)
Run it — the name holds the updated value:
Score: 40

score = score + 40 runs right-to-left: compute 0 + 40, then rebind score to 40. That read-compute-rebind move is how state advances.

3In our world

Now two names tracking a live game. On a hit we reassign score to its old value plus 250; when an enemy slips through, lives drops by one:

python
score = 0
lives = 3

score = score + 250
lives = lives - 1

print("Score:", score)
print("Lives:", lives)
Run it — the names now hold the updated state:
Score: 250
Lives: 2

score = score + 250 reads right-to-left: compute 0 + 250, then bind score to 250. Python has a shortcut for this exact move — score += 250 does the same thing.

The same idea, everywhere

State everywhere is just variables changing over time: a sprite's x each frame, a running total in a backtest, a count of DNA bases. The pattern — read the current value, compute a new one, rebind the name — is identical across every domain.

Try it yourself

Add high_score = 1000, then later check whether score beat it with a comparison. Next, rewrite score = score + 250 using the += shortcut and confirm the output is unchanged.

The common mistake

Reading score = score + 250 as a math equation. It is not a claim that both sides are equal — it is an instruction: evaluate the right side, then rebind the left name. That is why it makes perfect sense in code but would be nonsense in algebra.

What it unlocks

Named, changing values are the basis of conditionals that react to state, operators that compute new values, and f-strings that format them for display.

Want the simpler version? Read the Kids version →