Python Math Module
The math module is a module that holds maths helpers. Square roots, rounding, and pi all live in the math module.
Square roots and powers
sqrt() undoes squaring. pow() raises a number to a power.
import math
print(math.sqrt(16))
print(math.pow(2, 3))Round down and round up
floor() drops down to the whole number below. ceil() jumps up to the whole number above.
import math
print(math.floor(3.7))
print(math.ceil(3.2))The pi value
pi is a value in math, not a function. You do not call it with brackets.
import math
print(math.pi)Shared factors and factorials
gcd() finds the biggest number that divides both inputs. factorial() multiplies a number by every whole number below it.
import math
print(math.gcd(12, 18))
print(math.factorial(5))Some helpers need no import
abs() and max() are built in. They work with no import line.
print(abs(-7))
print(max(3, 9))Example
import math
radius = 5
area = math.pi * math.pow(radius, 2)
print(f"Circle area: {area:.2f}")
hyp = math.sqrt(math.pow(3, 2) + math.pow(4, 2))
print(f"Hypotenuse: {hyp}")
print(f"Area rounded down: {math.floor(area)}")
print(f"Area rounded up: {math.ceil(area)}")Key points
- Use import math to use the math module
- Maths helpers such as sqrt() and pi sit ready in the math module.
- Use math.sqrt() to get the square root of a number
- Use math.floor() and math.ceil() to round down and up
- math.pi holds the value of pi
In this example, the program reports on a circle and a triangle. It finds the circle area with math.pi and math.pow(). It prints that area with two decimal places. Then it finds the hypotenuse with math.sqrt(). Last, it rounds the area down with math.floor() and up with math.ceil().
Note
math.sqrt() always gives a float.
Even math.sqrt(16) gives 4.0, not 4.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
Which line gives the square root of 9?