Course Progress43%
🍎 Python Basics Topic 43 / 100
⏳ 7 min read

The math Module

Powers, roots, logarithms, trigonometry, and constants — Python’s built-in scientific calculator, ready to import.

"Python’s math module gives you every function you’d find on a scientific calculator — plus constants like pi and e, precise to full floating-point accuracy."

— ShurAI

Constants

python
import math

print(math.pi)    # 3.141592653589793  — pi
print(math.e)     # 2.718281828459045  — Euler’s number
print(math.tau)   # 6.283185307...     — 2 × pi
print(math.inf)   # inf               — positive infinity

Rounding — floor, ceil, trunc

python
print(math.floor(4.9))    # 4  — always rounds DOWN
print(math.ceil(4.1))     # 5  — always rounds UP
print(math.trunc(4.99))   # 4  — chops the decimal, no rounding

# Practical use: billing by pages (always charge whole pages)
pages   = 2.3
charged = math.ceil(pages)
print(f"Printed {pages} pages — charged for {charged}")
# Printed 2.3 pages — charged for 3
floor(4.9)
4
Always down
ceil(4.1)
5
Always up
trunc(4.9)
4
Chop decimal

Powers and Roots

python
print(math.sqrt(144))        # 12.0   — square root
print(math.isqrt(17))        # 4      — integer square root (no decimal)
print(math.pow(2, 10))        # 1024.0 — 2 to the power of 10
print(27 ** (1/3))            # 3.0    — cube root trick
print(math.hypot(3, 4))       # 5.0    — hypotenuse: √(3²+4²)

Logarithms

python
print(math.log(math.e))        # 1.0   — natural log (base e)
print(math.log(100, 10))       # 2.0   — log base 10 of 100
print(math.log10(1000))        # 3.0
print(math.log2(64))            # 6.0   — log base 2 (2&sup6;=64)

Trigonometry

python
# All trig functions use RADIANS — convert from degrees first
angle_deg = 90
angle_rad = math.radians(angle_deg)

print(math.sin(angle_rad))          # 1.0
print(math.cos(angle_rad))          # ~0.0
print(math.degrees(math.pi))        # 180.0 — pi radians = 180°

Real Example — Circle Calculator

python
import math

def circle_stats(radius):
    """Print area and circumference of a circle."""
    area  = math.pi * radius ** 2
    circ  = 2 * math.pi * radius
    print(f"Radius        : {radius} cm")
    print(f"Area          : {area:.2f} cm²")
    print(f"Circumference : {circ:.2f} cm")

circle_stats(7)
print()
circle_stats(3.5)
output
Radius        : 7 cm
Area          : 153.94 cm²
Circumference : 43.98 cm

Radius        : 3.5 cm
Area          : 38.48 cm²
Circumference : 21.99 cm

"math.floor() and math.ceil() solve more real-world problems than most trig functions — use them for pagination, billing, grid layouts, and anything that must land on a whole number."

— ShurAI

🧠 Quiz — Q1

What is the difference between math.floor(4.9) and math.ceil(4.1)?

🧠 Quiz — Q2

What does math.sqrt(81) return?

🧠 Quiz — Q3

What is math.pi?

🧠 Quiz — Q4

Why must you convert degrees to radians before using math.sin()?