Variables are name tags

A variable is a name you stick on a value so you can use it later.

name = "Maya"
score = 12

Read = as "now refers to", not "equals". The right side is worked out first, then the name on the left gets attached to the result. That is why this line, which looks like nonsense in a maths class, is completely normal in Python:

score = score + 1

Python takes the current score (12), adds 1, and moves the name score onto the new value, 13. The old value is not kept anywhere.

Think of variables as name tags, not boxes. When you write b = a, you are not copying something into a new box; you are putting a second tag on the same value. For numbers and strings this difference rarely bites you, but it will matter later with lists.

Naming rules:

  • Letters, digits and underscores only, and no digit at the start. player2 is fine, 2player is an error.
  • Names are case-sensitive: Score and score are two different variables.
  • Python style uses snake_case: lowercase words joined by underscores, like high_score.
  • Pick names that say what the thing is. x tells you nothing; lives_left tells you everything.

Using a variable before you have created it gives a NameError. Python only knows names you have actually assigned, and order matters: the assignment has to run before the line that uses it.

Try it yourself

Edit it. Break it. Run it again.
name = "Maya"
score = 12
print(name, "has", score, "points")

score = score + 5      # take the old value, add 5, re-attach the name
print(name, "now has", score, "points")

best = score           # a second name tag on the same value
score = 0              # moving 'score' does not move 'best'
print("score:", score, "best:", best)
Ctrl/Cmd + Enter runs. Esc, then Tab, leaves the editor.

Your turn

Type it yourself. That is the whole trick.

1Level up

The variable level starts at 3. Add a line that increases level by 2 using level = ..., so that the program prints Level: 5. Do not change the print line or type the number 5 anywhere.

level = 3
# your line goes here
print("Level:", level)
Ctrl/Cmd + Enter runs. Esc, then Tab, leaves the editor.

2Swap the names

a holds "left" and b holds "right". Swap them so the program prints right left. Use a third variable called temp to help. Do not change the first two lines or the last line.

a = "left"
b = "right"
# swap a and b here
print(a, b)
Ctrl/Cmd + Enter runs. Esc, then Tab, leaves the editor.

Code editor. Press Control or Command plus Enter to run the code. Tab indents; to move focus out of the editor, press Escape and then Tab.