Python Basics · Getting Started · lesson 4 of 12
Numbers and arithmetic
about 12 minutes · free · runs in your browser
Step 1 of 2
Two kinds of number
Python has whole numbers (int) and decimals (float). You do not declare which is
which — 7 is an int, 7.0 is a float.
The arithmetic operators are mostly what you would expect:
| Operator | Meaning | Example |
|---|---|---|
+ - * | add, subtract, multiply | 3 * 4 → 12 |
/ | divide — always gives a float | 7 / 2 → 3.5 |
// | floor divide — throws away the remainder | 7 // 2 → 3 |
% | modulo — only the remainder | 7 % 2 → 1 |
** | power | 2 ** 10 → 1024 |
/ returning a float catches everyone out once: 4 / 2 is 2.0, not 2.
% looks obscure but earns its keep: n % 2 is 0 for even numbers, and
n % 5 == 0 tells you n is a multiple of five. You will use it constantly.
Your turn: with total = 47 and per_box = 10, work out how many full boxes you
can fill and how many are left over.
You start from this, and edit it in the browser:
total = 47
per_box = 10
# Set full_boxes and leftover.
Step 2 of 2
Converting between types
Reading a number from somewhere usually hands you a string, and "5" + 1 is an error
rather than 6 — Python refuses to guess whether you meant addition or joining.
Convert explicitly:
int("5")→5float("2.5")→2.5str(5)→"5"
round() is the other one you will reach for: round(3.14159, 2) gives 3.14.
The second argument is how many decimal places to keep.
Your turn: price_text holds a price as text. Turn it into a number, add 20% tax,
and round the result to two decimal places in total_price.
You start from this, and edit it in the browser:
price_text = "19.99"
# Convert, add 20%, round to 2 decimal places.