- Know what variables and constants are and when to use them (2.2.1–2.2.2)
- Use data type conversion functions (2.2.3, 2.2.9)
- Understand scope, global and local variables (2.2.4–2.2.6)
- Declare and use variables and constants (2.2.7–2.2.8)
Variables
A variable is a named storage location whose value can change while the program runs. Use one whenever a value is input, calculated or updated.
score = 0
score = score + 10
Constants
A constant is a named value that should not change while the program runs. Python has no special keyword, so by convention constants are written in UPPER_SNAKE_CASE at the top of the program.
VAT_RATE = 0.2
MAX_ATTEMPTS = 3
Use constants for fixed values such as rates and limits. If the value changes in future, you edit it in one place, and the name explains what the number means.
Data type conversion
Conversion functions change a value from one type to another, so that operations between types work. The ones in the specification are int(), float(), str() and bool().
age = int(input("Age: ")) # "17" becomes 17
price = float("4.99") # 4.99
message = "You are " + str(age) # join a number to text
print(bool(0), bool(5)) # False True
Converting text that is not a number, such as int("ten"), causes a ValueError, so input should be validated first.
Scope
Scope is the part of a program where a variable can be used.
- Global variable: created outside any function; can be read anywhere in the program.
- Local variable: created inside a function; only exists while that function runs and cannot be used outside it.
TOTAL_STOPS = 20 # global (a constant)
def percent_done(done):
percent = done / TOTAL_STOPS * 100 # local
return percent
print(percent_done(5)) # 25.0
# print(percent) would fail: percent is local
Prefer local variables. They avoid one part of a program accidentally changing a value used elsewhere, and make functions easier to test and debug. Use globals only when a value is genuinely needed everywhere.