Variables and Constants

beginner20 min

Learning objectives

  • Distinguish between variables and constants
  • Explain why constants improve readability and maintainability
  • Use named constants appropriately in Python

Learn

AQA 4.1.1.6 — Variables and constants

Retrieval: you've been using variables since Sequence 1's very first lesson — this lesson asks why a value should sometimes be a variable and sometimes a named constant, a distinction that's easy to skip past but matters for writing maintainable programs.

Variables vs constants

A variable's value is expected to change while the program runs. A named constant's value is fixed for the life of the program — it exists purely to give a fixed value a meaningful name.

VAT_RATE = 0.20        # named constant - never reassigned after this line
price = 19.99            # variable - will change as the program runs

total = price * (1 + VAT_RATE)

Python has no enforced constants — that's a common misconception

Unlike some languages, Python has no const keyword — nothing actually stops you reassigning VAT_RATE later. "Constant" in Python is a naming convention (ALL_CAPS with underscores), not a language feature. The benefit isn't that Python prevents the mistake — it's that a reader (including you, later) immediately recognises VAT_RATE as a fixed configuration value rather than something that varies during execution.

Why bother with named constants at all?

Compare:

total = price * 1.20

with:

VAT_RATE = 0.20
total = price * (1 + VAT_RATE)

The first version hides a "magic number" — a reader has to guess what 1.20 means, and if VAT changes, every occurrence of 1.20 scattered through the program has to be found and fixed individually. The second version names the value once; changing VAT_RATE updates every calculation that uses it, and the code documents its own meaning.

Worked example — a currency converter

GBP_TO_USD_RATE = 1.27   # named constant - the exchange rate won't change mid-program

amount_gbp = float(input("Amount in GBP: "))
amount_usd = amount_gbp * GBP_TO_USD_RATE   # variable - a new result each run
print(f"£{amount_gbp:.2f} = ${amount_usd:.2f}")

GBP_TO_USD_RATE is a constant because within a single run of the program it never changes; amount_gbp and amount_usd are variables because they depend on whatever the user types in.

Challenge

Take a calculator program from an earlier lesson and identify any "magic numbers" it contains. Rewrite it so every fixed value is replaced with a clearly named constant, and explain in a sentence how this would make a future change (e.g. a VAT rate rising from 20% to 22%) safer to make.

Looking ahead: the next lesson (String Manipulation) and the file-handling lesson after it both rely on the same instinct — separating what's fixed about a program from what varies each time it runs.

Practise

Apply what you've just learned in the Coding Lab.

Open Coding Lab
Log in to track this lesson on your progress dashboard.
Log in