Variables

Store, change and name values in Python using variables and assignment.

About 3 min read
  • Explain what a variable is
  • Assign and update values in Python
  • Choose clear variable names
Before you start

You know how to use print to display text. Now your program will store values and use them later.

Named storage

A variable is a named place in memory that stores a value. You can think of it as a labelled box. Programs use variables to remember scores, names and calculation results. The value can change while the program is running.

Definition: variable

A named storage location whose value can change while a program runs.

Definition: assignment

Giving a value to a variable using the = operator.

Assigning and updating

Python assigns the value on the right to the name on the left. To update a variable, Python works out the right side first, using the current value, and then stores the result.

Python
score = 10
score = score + 5
print(score)

This program prints 15.

Try it: variablesEdit the code, then press Run.
Ready — press Run.

Naming rules

Use names that describe the data, such as total_price. In Python, names cannot start with a digit or contain spaces, and capital letters matter. Score and score are different variables.

Calculate a total

A shop sells 3 pens at 2 dollars each. Store the values and print the total.

Python
quantity = 3
price = 2
total = quantity * price
print(total)

Answer: The program prints 6.

Equals means assign

In Python, = stores a value. It does not ask whether two values are equal. Use == for that test.

Exam focus
Say it like this“A variable is a named location in memory whose value can change.”
Not like this“A variable is a word in code.” — Mention storage and that the value can change.
Common mistakeUsing a variable before giving it a value, or writing the assignment backwards as 5 = x.

Practice

Write a line that stores 16 in a variable named age.
age = 16
What is the value of x after x = 4 and then x = x * 2?
8
Is 2score a valid Python variable name?
No, because a variable name cannot start with a digit.
Going further
Swap the values of a and b using a third variable.
temp = a, then a = b, then b = temp.

Quick check

Variables quick check

What does x = 7 do in Python?

A single equals sign assigns the right side to the name on the left.

Which is the best variable name for a student's age?

It describes the data, starts with a letter and contains no spaces.

If n = 3, what is n after n = n + 1?

Python adds 1 to the current value, then saves that result.
Key takeaways
  • A variable stores a value under a name.
  • The = operator assigns a value.
  • Values can be updated while a program runs.
  • Descriptive names make code easier to read.