Variables — storing values
Give names to values so your program can remember, reuse, and update them as it runs.
- Assign a value to a variable using = and read it back
- Follow Python naming rules for variables
- Re-assign a variable and explain what changes
Imagine writing a recipe that says "take 350 grams of the thing, then add more of the thing, then put the thing in the oven." It is confusing because "the thing" has no name. Programming has the same problem: without names, you cannot refer back to values you have already computed.
A variable solves this. It is a name bound to a value. Once you have assigned a name, you can use that name anywhere you would otherwise repeat the value — and if the value ever changes, you only update it in one place.
Assignment with =
The assignment operator = binds a name on the left to a value on the right:
city = "Paris"
population = 2_160_000After these lines run, city refers to the text "Paris" and population refers
to the number 2160000. (The underscores in 2_160_000 are just visual separators
Python allows in number literals — they do not affect the value.)
Reading a variable back is as simple as using its name:
print(city) # Paris
print(population) # 2160000Run it, then change the values and run again. The print calls do not need to
change — they always use whatever the variable currently holds.
Naming rules
Python has a few hard rules and some strong conventions:
- Names can contain letters, digits, and underscores — but must not start with
a digit. So
score2is fine;2scoreis a syntax error. - Names are case-sensitive:
Cityandcityare two different variables. - Use lowercase_with_underscores for ordinary variables (this is the Python community standard, called snake_case).
- Avoid names that shadow Python built-ins like
list,print, ortype— you can technically do it, but it causes confusing bugs.
Good names describe what a value is, not what type it is. user_name is good;
string1 is unhelpful.
Re-assignment
A variable can be re-bound to a new value at any time. The old value is simply forgotten:
score = 0
print(score) # 0
score = 10
print(score) # 10
score = score + 5
print(score) # 15The line score = score + 5 reads the current value of score (10), adds 5 to
get 15, and then re-binds score to 15. The right-hand side is always evaluated
first, using the old value.
Python also lets you write score += 5 as shorthand for score = score + 5.
The same works for -=, *=, and /=. You will see this pattern constantly
in loops.
Exercise
Create a variable called city and assign it the string 'London'. Then create a variable called population and assign it the integer 9000000. Do not print anything.
city → 'London'population → 9000000Where to go next
Next: data types — integers, floats, strings, and booleans, and why the distinction matters.