← Back to Blog

Python Getting Math Dirty

The problem...

Basic arithmetic is fine for simple calculations.

But what about square roots? Powers? Rounding? Pi?

At some point, basic operators aren't enough.

The idea!

Python has a built-in module called math that gives you access to more powerful mathematical tools.

And this is your first time importing something. That's a big deal.

Your first import

To use the math module, you need to tell Python to load it first.

import math

That's it. One line at the top of your file. Now you have access to everything inside math.

Making it real

Think of it like this: Python comes with a toolbox. import opens a drawer you haven't opened yet.

The drawer was always there. You just needed to open it.

In practice

import math

print(math.pi)          # 3.141592653589793
print(math.sqrt(16))    # 4.0
print(math.pow(2, 8))   # 256.0
print(math.floor(3.9))  # 3
print(math.ceil(3.1))   # 4
print(math.abs(-5))     # 5

You access everything with math. — the dot tells Python where to look.

Rounding

Python also has a built-in round() — no import needed.

print(round(3.14159, 2))  # 3.14
print(round(3.5))          # 4
print(round(2.5))          # 2 — banker's rounding

round() takes two arguments — the number and how many decimal places you want.

Going further

import math

# Circle area
radius = 5
area = math.pi * math.pow(radius, 2)
print(f"Area: {area:.2f}")   # Area: 78.54

# Hypotenuse
a = 3
b = 4
c = math.sqrt(a**2 + b**2)
print(f"Hypotenuse: {c}")    # Hypotenuse: 5.0

What's really happening

import math loads a module — a collection of tools Python keeps separate to avoid cluttering your namespace.

Not everything is loaded by default. Python keeps it lean. You ask for what you need.

Heads up!

  • import goes at the top of your file — always
  • math.sqrt() always returns a float — even for perfect squares
  • math.floor() rounds down, math.ceil() rounds up — always
  • round(2.5) returns 2, not 3 — Python uses banker's rounding

The mindset shift

Stop thinking: "Python can only do basic math."

Start thinking: "Python has everything I need — I just need to know where to look."

What you should understand now

  • import loads additional tools into your program
  • The math module gives you sqrt, floor, ceil, pi, pow and more
  • round() is built-in — no import needed
  • You'll use import a lot — this is just the beginning
[ login to bookmark ] // copied! 39 views · 1 min
// resources
Code Example math_module.py
← prev int vs float — Know the Difference next → Your Second Mini Project — Make the Math Work
// 0 comments
// No comments yet. Be the first.
// leave a comment

// Your comment will appear after approval.