Names
Typing the same value over and over gets old. A name refers to a value so
you can use it again. You create one with =.
price = 40
print(price)
print(price * 3)
price = 40 means "from now on, price refers to 40". It does not mean
"price is equal to 40" in the maths sense. The value is on the right, the
name on the left, always.
Names can change
Assigning again replaces the old value.
stock = 10
print(stock)
stock = 7
print(stock)
The second print shows 7. The old value is gone.
A very common pattern is to update a name using its own current value:
stock = 10
stock = stock - 1
print(stock)
Read stock = stock - 1 right to left: compute stock - 1, which is 9, then
make stock refer to 9. Python has a shortcut for this: stock -= 1. The
same works for +=, *= and /=.
Names for strings
Any value can be named, including text.
item = "bread"
print(item)
print("You bought", item)
Choosing names
Names are made of letters, digits and underscores, and cannot start with a
digit. Python is case sensitive: Price and price are different names.
Use names that say what the value is. unit_price beats x.
Using a name before it exists is an error. Run this and read the message:
print(total)
NameError: name 'total' is not defined means exactly what it says: there is
no name total yet. You will see this error often. It almost always means a
typo or a forgotten line.
Try it
Name and print
Create a name item that refers to the text bread, then print the line
You bought bread using the name rather than typing the word again; that
is the skill being practised.
You bought bread
item = ...
print("You bought", ...)
Update stock
The shop starts the day with 10 loaves of bread. It sells 3. Starting from the
code below, reduce stock by 3 and then print it. Let Python do the
subtraction rather than typing 7 yourself; that is the skill being
practised.
7
stock = 10
# sell three loaves
print(stock)
Swap two names
first refers to "apple" and second refers to "bread". Make them swap,
so that first refers to "bread" and second to "apple", then print both
on one line, first then second.
bread apple
Do this using only the names, without writing "bread" or "apple" again;
moving values between names is the skill being practised.
first = "apple"
second = "bread"
# swap them
print(first, second)
Next: How a program runs.