Menu

A variable is a named location in the computer's memory where a value is kept. While the program runs, that value can change, so one name can hold one value near the start of a program and a different value later on.

One value at a time

At any moment a variable holds a single value. Assigning a new value replaces whatever was stored before, and the old value is lost โ€” the computer keeps no copy of it. If a variable is assigned the value 92 and later assigned 17, it now holds 17 and the 92 has gone.

The latest assignment is the one that counts: whenever the program uses the variable, it uses the value stored most recently. So one variable can be given a new value as many times as you like as the program runs.

# each assignment replaces the previous value
game_level = 'Forest'
game_level = 'Cave'
game_level = 'Castle'
print('Current level:', game_level)

Output:

Current level: Castle

Spotting variables in code

In a program, variables are the names that are given values and whose values can change. The quickest way to find them is to look for a name followed by a single equals sign, which assigns the value on the right to that name.

Not every value in a program is a variable. A fixed value written straight into the code, such as a number or some text in quotation marks, is just data: it has no name and it cannot change. In game_level = 'Castle', game_level is a variable because it is a name holding a value, while 'Castle' is a fixed value. Function names such as print are not variables either.

A variable name can appear anywhere its value is needed, including inside print(); it is still the same variable, holding whatever value it has at that point in the program.

Practise this