Definition
How does a game remember your score from one moment to the next?
A variable is a name that refers to a value stored in memory. It is created with the assignment operator =, which stores the value on the right under the name on the left. Assigning again replaces the value, so variables can change as the program runs.
In simple words
Think of a labelled box. score = 0 puts 0 in a box labelled score. score = score + 10 takes what is in the box, adds 10, and puts the result back. The label stays the same; what's inside changes.
Overview
- A variable is a name that refers to a value stored in the computer's memory.
- Assignment uses =: score = 85 makes the name score refer to the value 85.
- Names may contain letters, digits and underscores, cannot start with a digit and are case-sensitive.
- Python variables have no fixed type; the same name can later refer to a value of another type.
- Good names describe meaning (total_marks, not tm), use snake_case and avoid Python keywords.
- Multiple assignment (a, b = 1, 2) and swapping (a, b = b, a) are common Python patterns.
Why it matters
Every program stores information: a user's name, a running total, a model's accuracy. Variables are how. Good names, such as total_marks instead of t, make code readable for others and for you next month.
Key terms
- Variable
- A name that refers to a value stored in memory.
- Assignment
- Storing a value under a name with =.
- Identifier
- The name given to a variable, function or other object.
- Reassignment
- Giving an existing name a new value.
- Augmented assignment
- A shortcut such as += that updates a variable using its old value.
- Keyword
- A word reserved by Python, such as if or for, that cannot be used as a name.
Types
Variables can be classified by the role they play in a program. Computer-science teachers use these roles, described by Jorma Sajaniemi, to understand any program quickly.
1. Fixed value (constant)
A variable given a value once that never changes while the program runs.
- How it works: It is assigned at the start and only read afterwards; Python has no true constants, so by convention its name is written in capitals.
- Example: PASS_MARK = 33 or GST_RATE = 0.18.
- When to use it: Use it for limits, rates and settings, so a change is made in one place only.
2. Stepper (counter)
A variable that moves through a predictable sequence of values.
- How it works: It starts at a value and changes by a fixed step each time, usually as a loop counter or index.
- Example: for i in range(1, 11) steps i through 1 to 10; count = count + 1 counts items.
- When to use it: Use it to count, number items or move along a list.
3. Gatherer (accumulator)
A variable that collects the combined effect of many values.
- How it works: It starts at a neutral value (0 for sums, 1 for products, an empty list) and is updated with each new value in a loop.
- Example: total = 0, then total += mark for every mark, gives the sum of all marks.
- When to use it: Use it for totals, averages, products and building result lists.
4. Most-wanted holder
A variable that remembers the best value seen so far, such as the largest or smallest.
- How it works: It starts with the first value (or a very small or large number) and is replaced whenever a better value appears.
- Example: highest = marks[0]; if m > highest: highest = m finds the top score.
- When to use it: Use it to find maxima, minima, the cheapest item or the nearest city.
5. Flag (one-way flag)
A true-or-false variable that records whether something has happened.
- How it works: It starts as False and is set to True when a condition is met; later code checks it to decide what to do.
- Example: found = False; inside a search loop, found = True when the roll number matches.
- When to use it: Use it to remember a yes-or-no fact across many steps, such as an error or a match.
6. Temporary
A variable that holds a value for a very short time, usually during a swap or a calculation.
- How it works: It stores an intermediate result so it is not lost or recomputed, then is no longer needed.
- Example: temp = a; a = b; b = temp swaps two values (in Python, a, b = b, a does it directly).
- When to use it: Use it to keep long expressions readable or to hold a value during an exchange.
Explained in detail
Names point to values
A helpful way to picture a Python variable is as a label tied to a value, not as a box containing it. When you write score = 72, Python creates the value 72 somewhere in memory and ties the label score to it. When you then write score = 80, the label moves to a new value 80. If you write best = score, both labels now point to the same value. This picture explains later surprises with lists, where two names can point to the same changeable list, so a change through one name is visible through the other.
Naming well
| Rule or habit | Allowed or good | Not allowed or poor |
|---|---|---|
| Start with a letter or underscore | total, _count | 2nd_place |
| Only letters, digits and underscores | max_mark | max-mark, max mark |
| Not a keyword | class_name | class, for, if |
| Case-sensitive | total | Total, which is a different name from total |
| Descriptive (habit) | average_mark | a, x1, temp2 |
| snake_case (PEP 8 habit) | pass_count | PassCount, passcount |
Useful assignment patterns
- Augmented assignment: count += 1 means count = count + 1; there are also -=, *= and /=.
- Multiple assignment: x, y = 3, 4 assigns both at once.
- Swapping: a, b = b, a swaps two values without a temporary variable.
- Constants: by convention, names in capitals such as PASS_MARK signal values that should not change.
Dynamic typing
In Python, a variable has no fixed type; the value does. The same name can hold a number and later a string. This makes Python quick to write, but it means mistakes such as adding text to a number are only caught when the line runs. Many teams therefore add optional type hints, such as age: int = 15, which do not change how the program runs but let tools check for mismatches before running.
Python also lets you check whether two names point to the very same value with the is operator, and see a value's identity in memory with id(). For numbers and strings you will rarely need this, but it becomes useful when working with lists and other changeable objects, where knowing whether two names share one object prevents confusing bugs.
How it works
Naming rules
- Use letters, digits and underscores only, and don't start with a digit: score_2 is fine, 2score is not.
- Names are case-sensitive: Score and score are different.
- Don't use Python keywords such as if, for or class as names.
- Use snake_case: words in lowercase joined by underscores.
= is not 'equals' as in maths. It means 'store'. x = x + 1 makes perfect sense in Python: it adds one to x.
In code
A score that changes as the game goes on.
score = 0
print("Start:", score)
score = score + 10 # a coin
score = score + 25 # a gem
score += 5 # += is a short way to add
print("After collecting:", score)
lives = 3
lives -= 1
print("Lives left:", lives)
player_name = "Aarav"
print(player_name, "scored", score)Output
Start: 0 After collecting: 40 Lives left: 2 Aarav scored 40
Try it yourself
Valid or invalid name?
Can each be used as a Python variable name?
for
score2
total_marks
my score
2nd_place
Common mistakes
- Using a variable before giving it a value: NameError.
- Reading = as 'equals'. It means 'store the right side in the left'.
- Choosing names like x and temp2 that say nothing about the value.
Check yourself
Summary
- A variable is a name for a stored value; = stores it.
- Reassigning changes the value; += and -= are shortcuts.
- Use clear snake_case names that follow the rules.
Finished reading?
Sources: W3Schools Python Tutorial