Part 02 / Topic 2 of 10
Numbers
| Type | Example | Note |
|---|---|---|
int |
42, -7, 1_00_000 |
Whole numbers, no size limit. _ is only for readability |
float |
3.14, 2.5e3 |
Decimal numbers |
complex |
3+4j |
Real + imaginary part (used in science/engineering) |
Real-world example: Pack 7 laddoos into boxes of 2.
print(7 / 2) # 3.5 (true division, always float)
print(7 // 2) # 3 (floor division: full boxes)
print(7 % 2) # 1 (remainder: laddoos left over)
print(2 ** 10) # 1024 (power)
print(-7 // 2) # -4 (floor goes DOWN, not toward zero)
print(round(3.14159, 2)) # 3.14
print(round(2.5), round(3.5)) # 2 4 (rounds to the even number on a tie)
z = 3 + 4j
print(z.real, z.imag, abs(z)) # 3.0 4.0 5.0
abs() gives the size of a number without its sign: abs(-7) is 7. For a complex number it is the distance from 0.
Float precision: Computers store floats in binary, so some decimals are not exact.
print(0.1 + 0.2) # 0.30000000000000004
print(0.1 + 0.2 == 0.3) # False
import math # loads the math module (import is taught in Part 7)
print(math.isclose(0.1 + 0.2, 0.3)) # True
For money, round at the end (
round(x, 2)) or use thedecimalmodule for exact values.
๐ Going deeper: A
floatis a 64-bit IEEE 754 number with about 15โ17 correct digits. That is whyround(2.675, 2)gives2.67: the stored value is really 2.67499999โฆ A safe money trick is to count whole paise in anint(you will do this in Exercise 7).
Done here? The practice set for Part 2 โ 8 exercises with solutions โ is on the part page.