Edexcel International Advanced Level Computer Science, point 7.1.2
A variable is a named memory location whose value can change while the program runs. A constant is a named value that stays the same throughout the program. Check the Programming Language Subset (PLS) for the exact features allowed in the exam.
a. Creation
In Python a variable is created the first time you assign a value to it: there is no separate declaration, and the data type comes from the value.
score = 0 # an integer
name = "Amy" # a string
price = 4.99 # a float
passed = True # a Boolean
Naming rules and conventions
- Names may contain letters, digits and underscores, and can't start with a digit.
- Names are case-sensitive:
Scoreandscoreare different. - Can't be a keyword (
if,for,class, ...). - Convention:
lower_case_with_underscoresfor variables, and meaningful names (total_price, notx).
Constants
Python has no true constants, so the convention is to use UPPER_CASE names and not to change them.
PASS_MARK = 40
MAX_ATTEMPTS = 3
GRAVITY = 9.81
Why use constants? A named constant:
- Explains the meaning of a value (
PASS_MARKinstead of a mysterious40). - Is changed in one place if the value changes.
- Reduces typing mistakes.
b. Assignment
Assignment stores a value in a variable, using =. The right side is worked out first, then stored in the left.
count = 5
# now 6: uses the old value, stores the new one
count = count + 1
count += 1 # shorthand: now 7
a, b = 3, 4 # assign two at once
a, b = b, a # swap the values: a=4, b=3
x = y = 0 # both set to 0
Other shorthand operators: -=, *=, /=, //=, %=.
Reading input stores a string, so convert it when needed:
age = int(input("Age: "))
c. Access
Accessing a variable means using its value, by writing its name.
price = 4.99
quantity = 3
total = price * quantity # accesses both variables
print("Total:", total)
- Accessing a variable that hasn't been assigned is a
NameError. - The variable keeps its value until it is assigned again.
Scope
- A local variable is created inside a subprogram and exists only there (and while it runs).
- A global variable is created outside all subprograms and can be read anywhere. To change a global inside a subprogram, declare it with
global, though passing parameters is better practice.
KM_PER_MILE = 1.609 # global
def miles_to_km(miles):
km = miles * KM_PER_MILE # km is local, KM_PER_MILE is read
return km
(Scope and its benefits are covered in more depth in 9.1.2.)
Types of data in variables
Python variables can hold any type, and the type can change if you assign a different value:
x = 5 # int
x = "five" # now a str
print(type(x)) # <class 'str'>
(Data types are in 8.1.1.)
Worked example
Task: rewrite this code to use good variable and constant practice.
a = 2.5
b = float(input())
c = a * b * 0.9
print(c)
Improved:
PRICE_PER_KG = 2.5
DISCOUNT = 0.9 # 10% off
weight = float(input("Weight (kg): "))
cost = PRICE_PER_KG * weight * DISCOUNT
print("Cost:", cost)
Improvements:
- Meaningful names show what each value is.
- Only the values that never change while the program runs (the price per kg and the discount) are named constants in capitals, so they can be changed in one place.
- The weight is a variable, because it is different every time the program runs.
- The result has a clear name (
cost), and the input and output have labels.
Exam tip: use meaningful names and named constants for fixed values: this earns marks in Unit 2 and in 9.2.2 (readability). Remember that input() gives a string. Access a variable only after it has been assigned.
Check yourself
How is a variable created in Python?
By assigning a value to a name; there is no separate declaration, and the type comes from the value.
What is the convention for naming constants in Python?
Upper case with underscores, such as MAX_ATTEMPTS, and not changing them in the program.
What are the values of a and b after a, b = 3, 4 and then a, b = b, a?
a is 4 and b is 3.
Why use a named constant instead of the number itself?
It explains what the value means, it only needs changing in one place, and it avoids typing mistakes.