After this lesson you can store values under names, change them, and choose names that make your programs easy to read. Variables appear in every program you will ever write, so it is worth getting a comfortable feel for them now.
Creating a variable
A variable is a name that refers to a value. You create one by writing the name, an equals sign and the value:
shop_name = "Corner Shop"
items_sold = 18
unit_price = 45
print(shop_name)
print(items_sold)Corner Shop
18There is no keyword like var or let, and you do not declare a type. Python sees the line and works out the rest. The single = is called assignment. It does not mean "equals" as in mathematics. It means "make this name refer to that value".
Once a variable exists you can use it anywhere you could use the value itself:
revenue = items_sold * unit_price
print("Revenue:", revenue)
print(shop_name, "earned", revenue)Revenue: 810
Corner Shop earned 810Python looks up each name, finds the value, and carries on.
Changing a variable
Variables are called variables because they can vary. Assign again and the name points at a new value:
items_sold = 18
items_sold = 25
print(items_sold)25The old value is simply forgotten. You can also use the old value to work out the new one:
items_sold = items_sold + 1
print(items_sold)26This looks odd if you read = as equals, because a number cannot equal itself plus one. Read it as an instruction instead: work out the right side first, using the current value, then attach the name to the result. Python also has a shorthand, items_sold += 1, which does the same thing.
Python does not stop you changing the kind of value a name holds:
quantity = 5
quantity = "five"
print(quantity)fiveThat is allowed, but it usually makes programs confusing. Keep one name for one kind of thing.
A better picture than a box
Many people imagine a variable as a box holding a value. In Python a label on a value is closer to the truth. Two names can point to the same value:
a = 10
b = a
a = 20
print(a, b)20 10b still shows 10. When we wrote b = a, b was attached to the value 10. Later a was moved to 20, which did not affect b. Numbers and text cannot be changed in place, so for now you can safely think of each assignment as a fresh label.
Naming rules
Python has firm rules for names:
- Use letters, digits and underscores.
- Do not start with a digit.
- No spaces or hyphens.
- Case matters, so
priceandPriceare different. - Do not use Python's reserved words, such as
if,fororclass.
Breaking a rule gives a syntax error:
2nd_item = "tea"SyntaxError: invalid syntaxThe conventional style is snake case: lowercase words joined with underscores, like unit_price. Choose names that say what the value means. unit_price beats p, and customer_count beats n. Short names such as i are fine for tiny, obvious cases, which you will see in loops.
Using a name before it exists
A variable only exists after you assign it. Asking for one that was never created gives an error:
print(discount)NameError: name 'discount' is not definedThis is a NameError. The most common causes are a typo, or a name used before the line that creates it. Python runs from top to bottom, so order matters.
Variables in a bigger picture
Why bother with variables at all? Imagine a receipt program that prints the price in five places. If you typed the number 45 five times and the price changed, you would have to find and edit every copy, and one missed copy would give a wrong receipt. With a variable, you change one line and every place that uses the name follows.
Variables also give numbers meaning. The expression 45 * 3 tells the reader nothing, while unit_price * quantity tells them what is being calculated. Programmers call a bare number with no explanation a magic number, and replacing magic numbers with named values is one of the easiest ways to make a program clearer.
Finally, variables let a program remember. Everything the program has worked out so far lives in variables, and later lines can use it.
Common mistakes
- Reading
=as "equals". It is assignment. Comparison uses==, which later lessons cover. - Misspelling a name.
unit_priceandunit_priseare different. The result is aNameError. - Different capitalisation.
Totalandtotalare not the same variable. - Reusing one name for unrelated things. It makes code hard to follow.
- Using reserved words or a built-in name such as
printas a variable. Assigningprint = 5hides the realprintfor the rest of the program.
Exercise
A bookshop sells 12 books at 150 each and gives a flat discount of 200. Use variables for the number of books, the price and the discount, then print the amount to pay.
Show one possible answer
books = 12
price = 150
discount = 200
to_pay = books * price - discount
print("To pay:", to_pay)To pay: 1600Naming each number makes the calculation readable, and it means that if the price changes you only edit one line.
Next: explain your code with comments and style.
Key points
- A variable is a name attached to a value. You create one with = and no special keyword.
- A variable can be reassigned to a new value at any time, even one of a different type.
- Names use letters, digits and underscores, cannot start with a digit and are case sensitive.
- Use clear lowercase_with_underscores names so the code explains itself.