AQA GCSE Computer Science (8525), section 3.2.2 (Programming concepts)
Variables
A variable is a named place in memory that stores a value which can change while the program runs.
Constants
A constant is a named value that cannot change while the program runs. It is set once at the start.
Assignment
Assignment stores a value in a variable. In AQA pseudo-code it uses the arrow ←. The right-hand side is worked out first, then stored.
score ← 0
name ← "Sam"
score ← score + 10
CONSTANT VAT ← 0.2
score ← score + 10 means "take the current value of score, add 10 and store the result back in score".
Declaring
In some languages you must declare a variable (state its name and type) before using it. In Python, a variable is created when you first assign to it.
score = 0
name = "Sam"
score = score + 10
VAT = 0.2 # a constant, written in capitals by convention
print(score, name, VAT * 100) # 10 Sam 20.0
Python does not stop you changing a constant. Writing its name in capitals is a convention to say "do not change this".
Why use named constants and variables?
- Readability:
price * VATis easier to understand thanprice * 0.2. - Easy to change: if the VAT rate changes, change one line, not every place the number appears.
- Fewer mistakes: a name cannot be mistyped as easily as a long number.
- Variables let a program store data that changes, such as a score.
Meaningful identifier names
An identifier is the name you give to a variable, constant or subroutine. Use names that say what the value is for.
| Poor | Better |
|---|---|
x |
number_of_lives |
a1 |
player_name |
calc |
calculate_total |
Meaningful names make programs easier to read, check and maintain, for you and for other people. Examiners also expect them in your answers.
Common mistake: writing 5 = x or x = 5 as if it were maths. In pseudo-code, assignment goes right to left: the value on the right is stored in the variable on the left. Also, a constant should not be changed anywhere else in the program.
Exam tip: if asked why to use a constant, give two reasons: it is easier to read and it only needs to be changed in one place. Always use meaningful names in your own code answers.
Check yourself
What is the difference between a variable and a constant?
The value of a variable can change while the program runs, but the value of a constant cannot.
What is the value of score after: score ← 4, then score ← score * 2?
Give one reason for using meaningful identifier names.
The program is easier to read, understand and maintain.