iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Python Numbers

Python has three numeric types — int, float, and complex — and operators that behave consistently across them.

Arithmetic

OpMeansExample
+ - * /Add, subtract, multiply, divide (always float)7 / 2 == 3.5
//Floor division7 // 2 == 3
%Modulo7 % 2 == 1
**Power2 ** 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

Test yourself

Q1. In Python, int range is…
Q2. For money, prefer…
Q3. 7 // 2 returns…

Discussion

Loading…