🔢 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).
Meet the math module
floor always rounds down, ceil always rounds
up. Try math.ceil(4.0001).
floor, ceil, int and round
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 vertical line marks the number. floor lands on the bar's left end, ceil on its right end.
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!
Real-world math
math.hypot(3, 4) computes the same distance in one call. Try it!
Pizza geometry
A round pizza has a radius of 15 cm. Using
math.pi, compute:
area= π × radius²circumference= 2 × π × radius
Why does sqrt(25) fail with a NameError after import math?
It must be written math.sqrt(25)
You need import sqrt too