Python — Math
Operators recap + extras
10 / 3 # 3.333… true division (always float)
10 // 3 # 3 floor division
10 % 3 # 1 remainder
2 ** 10 # 1024 power
divmod(10, 3) # (3, 1) quotient AND remainder together
divmod shines in time conversions:
h, rem = divmod(7384, 3600)
m, s = divmod(rem, 60) # 2h 3m 4s
Built-in numeric functions
abs(-7) # 7
round(3.14159, 2) # 3.14 round-half-to-EVEN quirk: round(2.5) → 2!
max(3, 7, 5); min(...)
sum([1, 2, 3], start=10) # 16
That round(2.5) == 2 surprises everyone — banker's rounding. For half-up use int(x + 0.5) on positives or decimal module.
The math module
import math
math.floor(4.9); math.ceil(4.1)
math.sqrt(81) # 9.0
math.isqrt(81) # 9 integer sqrt — exact for big ints!
math.pow(2, 8) # 256.0
math.factorial(5) # 120
math.gcd(12, 18) # 6
math.pi; math.e; math.inf; math.nan
Trig takes RADIANS:
math.sin(math.pi / 2) # 1.0
math.degrees(math.pi) # 180
math.radians(90) # 1.5707…
Logarithms with bases:
math.log(1000) # natural ln ≈ 6.9
math.log10(1000) # 3.0
math.log2(8) # 3.0
Random numbers
import random
random.random() # [0.0, 1.0)
random.randint(1, 6) # inclusive dice
random.uniform(1.5, 3.5) # float range
random.choice(["a", "b"]) # one item
random.choices(pop, k=3) # WITH replacement
random.sample(pop, 3) # WITHOUT replacement — unique picks
random.shuffle(deck) # in-place shuffle
Reproducibility for tests:
random.seed(42) # same "random" sequence every run
Security note: tokens need secrets.token_hex(16), not random.
Floating-point precision
0.1 + 0.2 == 0.3 # False 😱
round(0.1 + 0.2, 10) == 0.3 # True
from decimal import Decimal
Decimal("0.1") + Decimal("0.2") # Decimal('0.3') exact — money-grade
Mini Practice
- Seconds → "2h 03m 04s" via divmod.
- Compare round/floor/ceil/trunc on ±values.
- Dice-roll tally over 600 throws using randint.
- Sample 5 unique lottery numbers from 1–49.
- Exact 0.1+0.2 via Decimal.
Next: JSON →
Related Topics
Frequently Asked Questions about Math
What is Math in Python?
Math is a fundamental concept in Python. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Math?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Math.
Why is Math important in Python?
Math is essential for Python development. Understanding this concept will help you write better code and solve real-world problems more effectively.