← All lessons
Python basics · Lesson 2 of 10

Variables

A value is a piece of data: the number 12, the text "Ana". Programs need to remember values and use them later, and for that they use variables. A variable is a name stuck on a value, like a label on a jar.

You make one with =. age = 12 means "store 12 under the name age". After that, writing age anywhere gives you 12. Making a variable this way is called assigning it.

age = 12
name = "Ana"
print(name)
print(age)
print(name, "is", age)
Prints
Ana
12
Ana is 12

Notice that name has no quotes when you use it. With quotes, "name" is just the four letters n-a-m-e; without them, Python looks up the variable called name and uses its value.

The = sign doesn't mean "equals" as in maths. Read it as becomes. Python works out the right side first, then stores the result under the name on the left. That's why a variable can be changed using its own old value:

points = 10
points = points + 5
print(points)
points = 0
print(points)
Prints
15
0

On line two, Python first works out points + 5 using the old value (10 + 5 is 15), then stores 15 back in points. Assigning a new value simply replaces the old one.

Naming rules: names can use letters, digits and underscores (_), but can't start with a digit and can't contain spaces. Capitals matter, so Score and score are two different variables. Python programmers write multi-word names in lower case with underscores, like total_price. Choose names that say what the value means; future you will thank you.

Using a variable before you've assigned it is an error: Python says NameError: name 'x' is not defined. It also happens when you misspell a name, since to Python a misspelled name is just a different, unknown one.

Practice

What does this print?

city = "Lima"
print(city)
More info

Quick reference

valueA piece of data, like 12 or "Ana".
variableA name for a value. Write the name without quotes to use the value.
name = valueAssignment: work out the right side, then store it under the name. Read = as "becomes".
snake_caseThe Python habit for names: lower case words joined by underscores.
NameErrorPython doesn't know that name: not assigned yet, or misspelled.

Related courses