Variables and types
A variable is a name your program uses to find a value again.
Reach for it whenUse a variable instead of repeating a literal when the value has meaning, changes, or is reused; keep a literal when naming it would add no clarity.
Think of it likeA luggage tag. The tag is not the suitcase; it just lets you refer to the suitcase without carrying it around.
You write price = 20, and from then on the name price refers to the number 20. Later you can write price = 25 and the name refers to something else. Nothing is permanent.
There are four kinds of information you meet immediately. Whole numbers, called integers — 3, 100, -7. Numbers with a decimal point, called floats — 3.5, 0.001. Text, called strings, always written inside quotes — "hello". And true-or-false values, called booleans — written True and False, capitalised.
count = 3- Binds the name count to the value 3. No type declaration needed.
name, age = "Ada", 36- Assigns several names at once, left to right.
count += 1- Shorthand for count = count + 1. Also -=, *=, /=.
type(count)- Tells you what kind of value a name currently holds.
total = None- The “nothing yet” value, for a name that exists but has no answer.Test it with `if total is None:`, never == None.
MAX_TRIES = 5- A constant by convention. Capitals tell a reader not to reassign it; Python will not stop you.
Draw the name on the left and an arrow to an object on the right. Assignment can swing that arrow toward a different object, and two names can point to the same mutable object.
When Python evaluates `a + b`, it inspects the objects bound to those names and dispatches type-specific behaviour. That is why the same symbol adds numbers, joins strings, and rejects incompatible pairs.
If two variables refer to one list, changing it through either name changes the same list. Reassignment only moves one name, so confusing mutation with reassignment creates bugs that look like action at a distance.
- CPython — binds names in local, global, and built-in namespaces to Python objects.
- Jupyter Notebook — keeps names and their values in the live kernel between executed cells.
- "A variable is a box containing the object." Correction: in Python it is a name bound to an object.
- "The type belongs permanently to the name." Correction: the same name can later refer to a different kind of value.