Topic 1.1
Variables: Names That Point to Values
In one line
A variable is a name that points to a value, created with =. The name is a label stuck on the value, not a box that holds it: you can move the label to a different value at any time, and two names can point to the same value.
Think of it like this
Sticky labels on school bags. Two bags sit on a table, one blue and one red. A sticky label that says "Asha" is stuck on the blue bag. Tomorrow you peel it off and stick it on a red bag. You can also stick two labels, "Asha" and "Front row", on the same bag. The labels are names, the bags are values, and moving a label never changes the bag itself.
Words you'll meet
New words in this topic, in plain English. Come back here whenever one feels fuzzy.
- Variable
- A name that points to a value.
- Assignment
- The statement
name = valuethat attaches a name to a value. - Value
- A piece of data such as 30, "Asha" or True.
- Rebinding
- Pointing an existing name at a different value.
- Identifier
- The official word for a name you choose for a variable.
- Case-sensitive
- Capital and small letters count as different.
Ageandageare two names. - snake_case
- Lowercase words joined by underscores:
total_price. - Reserved word (keyword)
- A word with a fixed meaning in Python, such as
iforclass, that you cannot use as a name. - NameError
- The error Python raises when you use a name that does not exist.
Step by step
01Create a variable with =
price = 30 does two things. First Python makes the number 30 in memory. Then it attaches the name price to it. From now on, writing price anywhere later in the program means "the value 30".
Notice that nothing is printed. An assignment is silent: it only creates the name. Use print(price) when you want to see the value.
price = 30
print("price:", price)02Names are labels, not boxes
Many books say "a variable is a box that holds a value". Python does not work that way. The value lives in memory by itself. A name is only a label pointing at it.
This matters the moment you write b = a. No new value is made. Both labels point to the same 10. When you later write a = 99, only the a label moves. b still points to 10, so it prints 10.
a = 10
b = a # b is a second label on the same value 10
a = 99 # the label a moves to 99; b is untouched
print("a:", a, "b:", b)03Rebinding: the same name, a new value
A name can be pointed at a different value as often as you like. Python does not ask whether the new value is the same kind as the old one: price can be a number now and text later. Numbers, text and so on are different types, meaning kinds of value (Topic 1.6 covers them). That freedom to change kinds is called dynamic typing. It is convenient, and it is also a source of bugs, so keep one meaning for each name.
price = 30
price = 45 # rebinding: the label moves to 45
price = price + 5 # right side first: 45 + 5, then the name points to 50
print(price) # 5004Naming rules
Python has hard rules (breaking them is a SyntaxError) and soft habits. The hard rules: letters, digits and _ only; no digit first; no spaces; not a reserved word. The soft habit is snake_case with a meaningful word.
Because names are case-sensitive, student_name and Student_Name are two separate variables. Mixing them up is a classic cause of NameError.
student_name = "Asha" # good: says what it holds
Student_Name = "Ravi" # legal, but a different name (and bad style)
2fast = 10 # SyntaxError: starts with a digit
class = 5 # SyntaxError: class is reserved05Several names at once, and the swap
x, y = 3, 4 is called multiple assignment. Python builds the pair 3, 4 on the right (a pair like this is called a tuple; Phase 4 teaches tuples), then gives the first value to x and the second to y. p = q = 0 points two names at the same 0.
Swapping two values is a famous beginner puzzle. In many languages you need a third variable. In Python the right side is completely worked out before any naming happens, so x, y = y, x just works: it builds the pair (old y, old x) and then names it.
x, y = 3, 4
x, y = y, x
print(x, y) # 4 306del and NameError
del temp removes the name temp. The value it pointed to is cleaned up automatically if no other name points to it. Using a name that does not exist (never created, deleted, or misspelled) gives a NameError. Python often suggests the name you probably meant.
You rarely need del in everyday code. You will see far more NameErrors from typing mistakes than from del.
total = 10
print(totl) # NameError: name 'totl' is not defined. Did you mean: 'total'?Try it yourself
- 1
Predict, then run
In the first example, change
a = 99tob = 50(and leave the rest). Before you run, say whataandbwill print. Then run it and check. - 2
Swap three values
Write
a, b, c = 1, 2, 3. Then, with one line, rotate them soabecomes 2,bbecomes 3 andcbecomes 1. Print the three names.Hint: write
a, b, c = b, c, a. - 3
Count up
Write
count = 0, thencount = count + 1three times, then printcount. Explain to yourself why the right side uses the old value.
Code & diagrams
Predict the line `a: ... b: ...` before you run. Why is b still 10?
Expected output
price: 30
price: 45
a: 99 b: 10
x, y: 3 4
after swap: 4 3
p, q: 0 0The last line fails on purpose. Read the error from the bottom up: it names the missing variable.
Expected output
Asha Ravi
temp is 5
temp deleted
Traceback (most recent call last):
File "main.py", line 9, in <module>
print(temp)
^^^^
NameError: name 'temp' is not definedBreak it on purpose
Errors are the best teachers. Make each change, read the error, guess what went wrong, then reveal the answer.
Break #1
Start a name with a digit
Create a variable called 2fast.
2fast = 10Break #2
Use a reserved word as a name
Try to call a variable class.
class = 5Myth vs fact
Myth
A variable is a box that stores a value.
Fact
In Python a variable is a name pointing to a value. Two names can point to one value, and the value exists whether or not any name points to it. The box picture breaks the moment you write b = a.
Myth
x = 5 means x equals 5, just like in maths.
Fact
In maths x = x + 1 is impossible. In Python it is a normal instruction: work out x + 1, then point x at the answer. A single = assigns; comparing uses a double == (Topic 1.8).
Myth
You must say what kind of value a variable holds before using it.
Fact
Python needs no declaration. The type belongs to the value, not to the name, so the same name can point to a number now and text later (try to avoid that).
Pro corner
Extra depth for experienced readers. New to this? Skip it for now and come back later.
- ▸
In CPython every value is an object in memory with a type, an identity (
id(x), which is its address in CPython) and a reference count. At module level and in classes, a name is an entry in a dictionary (the namespace) that maps the text of the name to the object. Inside a function, CPython stores local names in numbered slots instead, which is faster (Topic 5.5 covers scope).b = acopies the reference, not the object. Topic 13.2 shows the reference counting in detail. - ▸
Small whole numbers (-5 to 256 in CPython) and some short strings are cached and reused, so two names for "the same" small value may genuinely share one object. This is an optimisation, not a rule of the language, which is why you must never use
isto compare numbers or text (Topic 1.8). Since Python 3.12 these shared objects are also immortal: their reference count is never changed. - ▸
Assignment is a statement, not an expression, so
if (x = 5)is a syntax error. The walrus operator:=(Python 3.8) is the expression form (Topic 2.9). A classic interview trap: a name assigned anywhere inside a function is local to that whole function, socount = count + 1on a globalcountraisesUnboundLocalError(Topic 5.5). In a chained assignmentp = q = []both names get the same object, evaluated once. - ▸
In the AI world a typical script is a pile of well-named variables:
learning_rate,batch_size,prompt,response. Clear names are how a teammate reads your experiment six months later. - ▸
Tools such as linters catch the typo
totlbefore you run the program (Topic 11.6). The best defence is still short functions and meaningful names.
Remember this
- 1
A variable is a name that refers to a value. You make one with the assignment statement:
price = 30. Read it as "let the namepricepoint to the value 30". The single=here is not the maths "equals" sign. It is an instruction: take the value on the right, and attach the name on the left to it. - 2
Python runs the right side first, then does the naming. In
total = apple + bananait works outapple + bananaand only then attaches the nametotalto the result. This is whycount = count + 1is a valid line: it reads the oldcount, adds 1, and then pointscountat the new number. - 3
Assigning to a name that already exists is called rebinding: the label moves to a new value and the old value is left alone. In
b = athe value is not copied:bis a second label on the same value. For numbers and text this never causes trouble, because those values cannot be changed in place. Phase 4 shows what happens with values that can change (lists and dictionaries). - 4
A name may use letters, digits and the underscore
_, but it cannot start with a digit and cannot contain spaces or a dash. Names are case-sensitive:score,ScoreandSCOREare three different names. A few words, such asclass,if,for,TrueandNone, are reserved by Python itself and cannot be used as names. - 5
Python programmers write names in snake_case: all lowercase, words joined by underscores, like
student_nameortotal_price. Choose names that say what the value means.price_per_pentells the next reader everything;xandp2tell them nothing. - 6
Python lets you assign several names in one line.
x, y = 3, 4givesxthe value 3 andythe value 4. The same idea gives Python's famous one-line swap,x, y = y, x, which needs no spare variable. The statementdel nameremoves a name; using it afterwards raises aNameError.
Explain it without notes
What happens in memory when Python runs price = 30?
Explain why b = a followed by a = 99 leaves b unchanged.
Why is count = count + 1 valid even though it looks impossible in maths?
What are Python's rules for naming a variable, and what is the usual style?
Practice
Create length = 8 and width = 5, then a variable area that is their product, and print Area: 40 using the variables.
Set a = 7 and b = 2, swap them in one line, and print both.
Write two variables with names that differ only by capital letters and print them. Explain what this shows.
Trade-offs
- ↔
Freedom to rebind vs. clarity. Python lets one name hold different kinds of value over time. That is quick to write, but a name that changes meaning is confusing. Keep one meaning per name.
- ↔
Short names vs. descriptive names.
nis fine for a tiny loop counter, butnumber_of_studentsis better for anything that lives longer than a few lines. Longer names cost typing and save reading.
Done when you can
Done when you can explain a variable using the sticky-label picture.
Done when you can predict the output of
b = afollowed bya = 99.Done when you can name three rules for a valid variable name and give an example in snake_case.
Done when you can swap two variables in one line.
Done when you can read a
NameErrorand find the misspelled name.