The programs in the last lesson could only print text that you had typed in advance. To calculate anything, a program has to remember things: a price, a count, a name. This lesson shows how.
A variable is a name for a value
A value is a piece of data, such as the number 4 or the text "notebook". A variable is a name that refers to a value, so that later statements can use the value by name.
You create a variable with an assignment statement: a name, an equals sign, then the value.
price = 4
print(price)This prints 4. Notice that price has no quotation marks. print("price") would print the word price; print(price) prints the value that the name refers to.
In Python, = does not mean "is equal to" as it does in maths. It means "from now on, this name refers to this value". Read price = 4 as "price becomes 4".
Three kinds of value
Every value has a type, which says what kind of data it is. You need three types for now:
| Type | Python's name | Examples |
|---|---|---|
| whole number (integer) | int |
3, 0, -12 |
| number with a decimal point (float) | float |
2.5, 0.1, 3.0 |
| text (string) | str |
"notebook", "3" |
The quotation marks matter: 3 is a number you can do arithmetic with, and "3" is a piece of text that happens to contain a digit.
Arithmetic
Python calculates with the symbols below, which are called operators.
print(7 + 2) # add
print(7 - 2) # subtract
print(7 * 2) # multiply
print(7 / 2) # divide
print(7 // 2) # divide and drop the remainder
print(7 % 2) # the remainderThis prints 9, 5, 14, 3.5, 3 and 1, one per line.
Two details are worth remembering:
/always gives a float, even when the answer is whole:10 / 5is2.0.- Multiplication and division happen before addition and subtraction, as in maths.
2 + 3 * 4is14. Use round brackets to choose a different order:(2 + 3) * 4is20.
Assignment works out the right-hand side first
The right-hand side of = can be a calculation, and it can use other variables. Python works the right-hand side out first, then makes the name on the left refer to the result.
price = 4
quantity = 3
total = price * quantity
print(total)
quantity = 5
print(total)This prints 12 and then 12 again. Step through the diagram to see why the second line of output is not 20.
total was given the value 12 when line 3 ran. Changing quantity later does not go back and recalculate it.A variable does not remember how its value was calculated. It refers to the finished result.
count = count + 1 makes sense: the old value is used first, then the name moves to the new value.count = 7
count = count + 1
print(count)This prints 8. As a maths equation, count = count + 1 would be nonsense. As an instruction it is ordinary: "work out count + 1, then call the answer count".
Choosing names
A variable name may contain letters, digits and underscores (_). It may not start with a digit, and it may not contain spaces. Capital letters count, so total and Total are two different names.
Python programmers write names in lower case with underscores between the words: unit_price, first_name. Choose names that say what the value means. price is better than p, and far better than x.
Putting values into printed text
print accepts several arguments separated by commas. It prints them on one line with a space between each.
item = "notebook"
quantity = 3
print("Item:", item)
print(quantity, "of them")This prints Item: notebook and 3 of them.
When you want full control of the spacing, use an f-string: a string with the letter f in front of the opening quotation mark. Inside an f-string, a name in curly brackets { } is replaced by its value.
item = "notebook"
price = 2.5
print(f"One {item} costs {price} pounds.")
print(f"Price: {price:.2f}")This prints One notebook costs 2.5 pounds. and Price: 2.50. The :.2f after a name means "show this number with exactly two digits after the decimal point", which is what you want for money.
There is a second reason to use :.2f. Computers store floats in a way that cannot represent every decimal exactly, so tiny errors appear:
print(0.1 + 0.2)
print(f"{0.1 + 0.2:.2f}")This prints 0.30000000000000004 and then 0.30. The first line is not a fault in your program; it is how floats behave in almost every programming language. Round the number when you display it.
Two errors you will meet
A misspelt variable name. Python only knows the names you have assigned.
total = 12
print(totl)Traceback (most recent call last):
File "main.py", line 2, in <module>
print(totl)
^^^^
NameError: name 'totl' is not defined. Did you mean: 'total'?Read the last line first: NameError means an unknown name, and the message quotes it. Line 2 is where Python met it. The fix is to spell the name the way it was assigned.
Joining text and a number with +. Between two strings, + joins them: "note" + "book" is "notebook". Between two numbers it adds. Python refuses to guess what you mean when you mix the two:
price = 3
print("Total: " + price)Traceback (most recent call last):
File "main.py", line 2, in <module>
print("Total: " + price)
~~~~~~~~~~^~~~~~~
TypeError: can only concatenate str (not "int") to strTypeError means an operation was given a type of value it cannot work with. "Concatenate" means join end to end, str is a string and int is an integer: Python is saying it can join a string only to another string, not to an integer. The fix is an f-string: print(f"Total: {price}").
What you can do now
You can give values names, calculate with integers and floats, update a variable, and build lines of output from text and values. In the exercises you will predict what assignments and calculations print, then write a program that works out and prints a receipt.
Next: read what the user types, so that the values can come from the person running the program.