Arithmetic: + - * /
🌍 In real life. At a grocery shop, the shopkeeper adds up your bill: 3 packets of biscuits at 20 taka each, plus 2 loaves of bread at 45 taka each, minus a 10 taka discount. It's easy to slip with so many numbers. A calculator never gets tired and never slips.
Python makes a great calculator, and unlike a calculator, it can keep the numbers in variables and use them again.
The idea in one sentence: Python works out maths with the four operators + - * /, and / always gives a float.
Its words:
- operator: a symbol that does a job with values:
+add,-subtract,*multiply (a star, not ×),/divide - expression: values and operators together, like
4 * 3, that Python works out to one value - result: the value an expression works out to
Step by step, for print(4 * 3):
- Python sees the expression
4 * 3inside the brackets. - It works it out: 4 multiplied by 3 is 12.
printshows the result,12.
Watch 4 * 3 as rows of blocks:
print(7 + 5)
print(10 - 4)
print(4 * 3)
print(12 / 4)How Python does it. +, - and * on two ints give an int. But / is different: it always gives a float, even when the answer is a whole number, because dividing can leave a part (7 / 2 is 3.5) and Python keeps the type the same every time.
Mixing an int and a float gives a float. Spaces around operators are optional, but they make code easier to read.
print(7 / 2)
print(8 / 2)
print(type(8 / 2))print(3 + 1.5)
print(2 * 2.0)
price = 20
quantity = 3
print(price * quantity)Mistakes and edge cases.
- × or x for multiply.
print(4 × 3)givesSyntaxError: invalid character '×' (U+00D7). Use*. - Leaving out the star. In maths, 2x means 2 times x, but
print(2x)givesSyntaxError: invalid decimal literal. Write2 * x. - Dividing by zero.
print(5 / 0)givesZeroDivisionError: division by zero. - Expecting a whole number from /.
12 / 4is3.0. (The next lesson shows//, which keeps whole numbers.) - Tiny decimal surprises. Computers store decimals in binary, so a few results come out a tiny bit off. It happens in every programming language:
print(0.1 + 0.2)Quiz
What does this print?
print(6 * 7)What does this print?
print(9 / 3)What does this print?
print(10 - 2.5)Which symbol multiplies in Python?
- x
- *
- ×
What does this print?
a = 5 b = 2 print(a / b)Which line stops this program with an error?
total = 10 people = 0 print(total / people)
Coding tasks
Pens cost 15 taka each, and you buy 4. Print the total cost using
priceandcount.Make a variable
halfthat holds 9 divided by 2.