- Explain what a variable is
- Assign and update values in Python
- Choose clear variable names
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.
A named storage location whose value can change while a program runs.
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.
score = 10 score = score + 5 print(score)
This program prints 15.
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.
A shop sells 3 pens at 2 dollars each. Store the values and print the total.
quantity = 3 price = 2 total = quantity * price print(total)
Answer: The program prints 6.
In Python, = stores a value. It does not ask whether two values are equal. Use == for that test.
Practice
Quick check
What does x = 7 do in Python?
Which is the best variable name for a student's age?
If n = 3, what is n after n = n + 1?
- 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.
