Python Numbers
Python has three numeric types — int, float, and complex — and operators that behave consistently across them.
Arithmetic
| Op | Means | Example |
|---|---|---|
+ - * / | Add, subtract, multiply, divide (always float) | 7 / 2 == 3.5 |
// | Floor division | 7 // 2 == 3 |
% | Modulo | 7 % 2 == 1 |
** | Power | 2 ** 10 == 1024 |
int is unlimited
PYTHON
print(2 ** 200) # 1606938044258990275541962092341162602522202993782792835301376
Beware float precision
PYTHON
print(0.1 + 0.2) # 0.30000000000000004
For money, use Decimal:
PYTHON
from decimal import Decimal
print(Decimal('0.1') + Decimal('0.2')) # 0.3
Built-in helpers
PYTHON
abs(-7) # 7 round(3.567, 2) # 3.57 min(3, 1, 2) # 1 max(3, 1, 2) # 3 sum([1, 2, 3]) # 6 divmod(7, 2) # (3, 1)
Tip: Use
Decimal for currency. Use fractions.Fraction for exact ratios. Reach for plain float only when ~15 digits of binary precision is enough.Example
Example
x = 7
y = 2
print('add', x + y)
print('div', x / y) # 3.5
print('intdiv', x // y) # 3
print('mod', x % y) # 1
print('pow', x ** y) # 49
Try it Yourself »
Exercise
Floor-divide 7 by 2.
print(7
2) # 3
Two slashes.
Discussion
Loading…