Number types
int— whole numbers of any size:7,-3,10_000_000(underscores for readability)float— decimals:3.14,1.5e3complex—2 + 3j(rarely needed)
Type conversion (casting)
int("25")→25,int(9.8)→9(cuts the decimal)float("3.5")→3.5str(100)→"100"int("abc")raises aValueError
Useful built-ins
abs(-5), round(3.14159, 2), pow(2, 10), max(), min(), sum(), divmod(17, 5) → (3, 2)
The math module
import math → math.sqrt, math.ceil, math.floor, math.pi, math.factorial
Random numbers
import random → random.randint(1, 6), random.choice(list), random.shuffle(list). Use the secrets module for passwords and OTPs.
Float precision
0.1 + 0.2 gives 0.30000000000000004. For money, use the decimal module or store amounts in paise as integers.
Example
Example — Number practice
Python
import math, random
from decimal import Decimal
price = "499"
qty = 3
total = int(price) * qty
print("Total:", total)
print(17 / 5, 17 // 5, 17 % 5, 2 ** 10)
print(round(3.14159, 2), math.sqrt(144), math.ceil(4.1))
print(0.1 + 0.2)
print(Decimal("0.1") + Decimal("0.2"))
print("Dice:", random.randint(1, 6))
print("Population:", f"{1_400_000_000:,}")
Output: Total: 1497, 3.4 3 2 1024, 3.14 12.0 5, 0.30000000000000004, 0.3, a random dice number, Population: 1,400,000,000