Variables: names for values

A variable is a name attached to a value. Learn assignment with =, how reassignment moves a name to a new value, and what happens when two names share one value.

Lesson · 15 min

In this lesson you will

  • Explain what a variable is, using the picture of a name tag on a value
  • Create and update variables with =
  • Read = as "now refers to", not "equals"
  • Predict what happens when one variable is copied into another and then changed
  • Choose clear, legal variable names

So far every value has been typed straight into a print. That works for one line, but real programs need to remember things: a score, a name, a running total. That’s what variables are for.

A name for a value

A variable is a name that refers to a value. You create one with an equals sign:

score = 10
print(score)

Read the first line as “score now refers to 10”. Python creates the value 10 somewhere in the computer’s memory and ties the name score to it. Later, when Python sees the name score, it looks up what the name refers to and uses that value instead.

This is called assignment: the name on the left gets the value on the right. The direction matters. 10 = score is an error, because you can’t give the number 10 a new meaning.

Variables make code readable. Compare these two cells. They do the same sum:

print(12 * 4.5)

hours = 12
rate = 4.5
print(hours * rate)

The second version tells you what the numbers mean. Six months from now, you’ll thank yourself.

Picture it: tags on boxes

Here’s a helpful picture. Memory is full of boxes, and each box holds one value. A variable is a name tag tied to a box with a piece of string. Step through the program below and watch the tags and boxes.

Loading the interactive graphic…

Think of memory as a shelf of boxes, each holding one value. Right now the shelf is empty.

Three things to notice:

  1. Reassigning moves the tag. score = 10 doesn’t scribble over the old box; it ties score to a different box. The box holding 0 has no tags left, so Python quietly cleans it up.
  2. best = score doesn’t copy anything. It ties a second tag to the box that score refers to right now. Two names, one value.
  3. Changing score later doesn’t change best. score = 25 moves only the score tag. best still refers to 10.

Try the playground under the program: invent your own names and values and watch what happens.

Predict, then run

This trips up almost everyone at first, so predict before you run: what does the last line print?

a = 5
b = a
a = 7
print(a, b)

It prints 7 5. Line 2 ties b to the value a referred to at that moment, which was 5. Line 3 moves a to 7 and leaves b alone. b = a is a snapshot, not a permanent link between the two names.

Updating a variable

A very common pattern is to work out a new value from the old one:

coins = 3
coins = coins + 2
print(coins)

In maths, “coins = coins + 2” would be nonsense. In Python it’s perfectly sensible, because Python works out the right-hand side first, using the current value (3 + 2 = 5), and only then moves the tag. So = doesn’t mean “is equal to”. It means “now refers to”.

Updating like this is so common that Python has a shortcut: coins += 2 means exactly coins = coins + 2. There’s also -=, *= and /=.

lives = 3
lives -= 1
lives -= 1
print("Lives left:", lives)

Instead of asking the user

Real programs often ask the person using them for information, with a function called input(). The cells on this site can’t stop and wait for typing, so we’ll do what programmers do when testing: put the “answer” in a variable at the top, and you change it. Edit name and year_born and run again:

name = "Sam"
year_born = 2012
age_this_year = 2026 - year_born
print(name, "turns", age_this_year, "this year")

Naming rules

Variable names can contain letters, digits and underscores, but they can’t start with a digit and can’t contain spaces. Python also reserves a few words for itself, like if, for and True, so you can’t use those.

FineNot allowedWhy
total2nd_placestarts with a digit
first_namefirst namecontains a space
player2classclass is a reserved word

Names are case sensitive: Score and score are two different variables. By convention, Python programmers write names in lowercase with underscores between words, like hours_worked. Pick names that say what the value means: price beats p, and p beats x.

A common mistake

If you use a name before giving it a value, Python stops with a NameError:

NameError: name 'totl' is not defined

Usually it’s a typo (totl instead of total) or you forgot to run the cell that creates the variable. On this site, cells share their variables like the pages of one notebook, so if a cell uses a variable from an earlier cell, run the earlier cell first.

Your turn

Exercise · Python

The piggy bank

Jo’s piggy bank starts with 20 coins. Write the story in code, one line per event, by updating the variable savings each time (use savings = savings + ... or +=):

  1. Start: savings is 20.
  2. Grandma gives Jo 15 coins.
  3. Jo spends 8 coins on a comic.
  4. Jo earns 5 coins for washing the car.

At the end, also create spent holding the number of coins spent (8). Don’t just type the final answer: the point is to practise updating a variable step by step.

savings = 20
# Grandma gives 15

# Spend 8 on a comic

# Earn 5 washing the car

print("Savings:", savings)

Check yourself

Self-check · 4 questions

Variables

1. What does x = 5 do?
2. After a = 5; b = a; a = 7, what is b?
3. After coins = 3 and then coins = coins + 2, what is coins?
4. Which is a valid variable name?