The math module

Numbers & Math, lesson 5 of 5

🔢 Numbers & Math, lesson 5 of 5

The math module

Import extra tools: square roots, pi, floor and ceil.

9 min

1 exercise

2 quizzes

0/3 solved

Getting Python ready… examples can run in a moment.

Python comes with a standard library of ready-made modules. The math module adds more math tools. Load it with import math at the top of your program, then use its contents with a dot: math.sqrt(16).

Example

Meet the math module

floor always rounds down, ceil always rounds up. Try math.ceil(4.0001).

Walkthrough

floor, ceil, int and round

-4-3-2-10123454.7-3.7
Step 1 of 2
floor = 4
ceil = 5
int = 4
round = 5

4.7 sits between 4 and 5. math.floor goes down to 4 and math.ceil up to 5. int() just chops off .7 (4), while round() picks the nearer one (5).

the whole numbers around it

The vertical line marks the number. floor lands on the bar's left end, ceil on its right end.

Quiz

What does this print?

ceil is perfect for "how many do I need?" questions: if 7 people need seats and a car has 4 seats, you need math.ceil(7 / 4) = 2 cars, not 1.75!

Example

Real-world math

math.hypot(3, 4) computes the same distance in one call. Try it!

Exercise

Pizza geometry

A round pizza has a radius of 15 cm. Using math.pi, compute:

  • area = π × radius²
  • circumference = 2 × π × radius
Quiz

Why does sqrt(25) fail with a NameError after import math?