Chapter 04 ยท Working With Data
Numbers & Math
Prices, totals, ages, scores โ numbers are everywhere in real programs. Python is a capable calculator, and the rules are refreshingly simple.
The basic operators
| Symbol | Means | Example | Result |
|---|---|---|---|
+ | Add | 10 + 3 | 13 |
- | Subtract | 10 - 3 | 7 |
* | Multiply | 10 * 3 | 30 |
/ | Divide | 10 / 3 | 3.333... |
// | Divide, whole number only | 10 // 3 | 3 |
% | Remainder (modulo) | 10 % 3 | 1 |
** | Power | 10 ** 2 | 100 |
price = 1500
quantity = 3
total = price * quantity
print(f"Total: K{total}")
Total: K4500
A real example: change from a note
cost = 1750
paid = 2000
change = paid - cost
print(f"Your change is K{change}")
Your change is K250
Turning text into numbers
Numbers that arrive as text (for example, typed by a user) must be converted before you can do maths.
Use int() for whole numbers and float() for decimals:
typed = "50"
real_number = int(typed)
print(real_number + 10)
60
Without int(), "50" + 10 would be an error โ you can't add text and a number.
โ๏ธ Try it yourself
A shop sells a book for K85. Work out and print the cost of 7 books, and the change from a K1000 note.
/ always gives a decimal
10 / 2 gives 5.0 (a float), not 5. If you need a whole number,
use // or wrap it in int(). The % remainder is secretly one of the
most useful operators โ it's how you check if a number is even: n % 2 == 0.
Recap
- Python does maths with
+ - * / // % **. /gives a decimal;//gives a whole number.- Convert text to numbers with
int()orfloat()before calculating.