Definition
A variable is a named container in a program that stores a value. The name acts as a label so that the program — and the programmer — can refer to that value without knowing its exact location in memory.
The word "variable" reflects the fact that the stored value can vary (change) over the course of a program's execution.
Examples
x = 5
name = "Alice"
temperature = 23.7
isActive = True
Here, x holds the integer 5, name holds the string "Alice", temperature holds a decimal number, and isActive holds a boolean.
Declaration vs Assignment
| Term | Meaning | Example |
|---|---|---|
| Declaration | Telling the program the variable exists | let score (JavaScript) |
| Assignment | Giving the variable a value | score = 0 |
| Initialisation | Declaration and assignment in one step | score = 0 (Python) |
In many languages (including Python) there is no separate declaration step — a variable comes into existence the moment you assign a value to it.
You can change the value stored in a variable at any time:
score = 0
score = score + 10 # score is now 10
The right-hand side of an assignment is always evaluated first. So score = score + 10 reads the current value of score (0), adds 10, and then stores the result (10) back into score.
Scope
Scope refers to the part of the program where a variable can be accessed.
- A local variable is declared inside a function and can only be used within that function.
- A global variable is declared outside all functions and can be accessed from anywhere in the program.
Using local variables wherever possible reduces the risk of accidentally modifying a value from an unrelated part of the code.
Choose descriptive variable names. A name like totalPrice is far more readable than tp or x3. Clear names make programs easier to understand, debug, and maintain.
Practice Problems
What is the value of x after: x = 3 followed by x = x * 2?
Show answer
What is the difference between a local and a global variable?