← Intro to programming with Python

Variables: names for values

Store a value once and use it again and again.

Start this lesson

A variable is a name that holds a value, like a jar with a label on it. The line age = 15 means "put 15 into the jar labelled age". The = sign here means STORE, not "is equal to" like in math. Why bother? You type a value once and use it as often as you like, and if it changes, you change it in one place instead of hunting through the whole program.

city = "Lima"
temperature = 22
print(city)
print("It is", temperature, "degrees in", city)

The first two lines store values. print(city) shows Lima, the value inside the jar. The last line mixes text and variables to show: It is 22 degrees in Lima.

Common mistake: putting quotes around a variable name. print("city") shows the word city, while print(city) shows what is stored in it (Lima).

Another common mistake: using a variable before you create it. Python runs from the top down, so print(price) above the line price = 4 gives a NameError, meaning "I don't know that name yet".

A variable can hold text (in quotes) or a number (no quotes).