Numbers
Python has whole numbers (int, like 42) and decimal numbers (float, like 3.14). You calculate with + - * /, use // for whole-number division, % for the remainder and ** for powers. Integers can be as large as you like.
The arithmetic operators
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ | Add | 7 + 2 | 9 |
- | Subtract | 7 - 2 | 5 |
* | Multiply | 7 * 2 | 14 |
/ | Divide (always a float) | 7 / 2 | 3.5 |
// | Whole-number division | 7 // 2 | 3 |
% | Remainder | 7 % 2 | 1 |
** | Power | 7 ** 2 | 49 |
print(7 / 2)
print(8 / 2)
print(7 // 2)
print(7 % 2)
print(2 ** 10)3.5 4.0 3 1 1024
Notice that 8 / 2 gives 4.0, not 4: the / operator always returns a float. Use // when you want a whole number.
Order of operations
print(2 + 3 * 4)
print((2 + 3) * 4)14 20
Python follows normal maths rules: powers first, then * / // %, then + -. Brackets make your intention clear.
Big integers
print(2 ** 100)
print(1_000_000 * 3)1267650600228229401496703205376 3000000
Python integers never overflow. Underscores like 1_000_000 are allowed in numbers just to make them easier to read.
Converting and rounding
text = "25"
print(int(text) + 5)
print(float("2.5") * 2)
print(round(3.14159, 2))
print(int(9.99))30 5.0 3.14 9
Why 0.1 + 0.2 isn't exactly 0.3
print(0.1 + 0.2)
print(round(0.1 + 0.2, 2))
from decimal import Decimal
print(Decimal("0.1") + Decimal("0.2"))0.30000000000000004 0.3 0.3
Computers store floats in binary, so some decimals can't be stored exactly. That's true in every language, not just Python. For money, use the decimal module or count in whole cents.
Practice
A trip costs 250 euros and is split between 3 friends. Print each friend's share rounded to 2 decimals, then on a second line the whole euros each pays (no decimals), then the euros left over.
83.33 83 1