What is a module?
A module is a file of pre-written Python code, packed with useful things like functions and constants, that you can pull into your own program. Instead of writing all that code yourself, you import the module and use its tools right away.
Think of it like a pegboard of tools in a workshop. You could build your own wrench from scratch every time you need one. Or you could walk over to the board and grab a wrench somebody already made, tested, and labeled for you. Modules usually focus on one topic, and today's topic is math.
Why it matters: understanding and taking advantage of modules is a huge part of writing real Python programs. Professional programmers import modules constantly, because rewriting code that already exists is a waste of time.
import math
The math module adds many common math functions and constants that the base Python language doesn't have on its own. And because it comes bundled with Python automatically, unlocking it takes exactly one line at the top of your program:
import math print("Toolbox unlocked!") print(math.sqrt(16))
Toolbox unlocked! 4.0
Once imported, you can access any function or constant with the pattern math.name. The math. part in front is like saying "hey, math module, hand me your..." followed by the tool you want:
- math.sqrt(16) asks the math module for its square root function
- math.pi asks it for the constant pi
Spot the 4.0: the square root of 16 printed as 4.0, not 4. Most math module functions hand back floats (decimal numbers), even when the answer is a whole number.
Try the toolbox tester
Take the tools off the pegboard yourself. Type a number, then click a tool to see the exact Python line and exactly what Python would print back. The dashed round(x) tool is a built-in, not part of the math module. More on that below.
Toolbox tester
Ceil vs floor visualizer: math.ceil pulls your number UP to the next integer, math.floor pulls it DOWN.
Try to break it: ask for math.sqrt(-4). There is no real-number square root of a negative, so Python refuses with a ValueError: math domain error. "Domain" is math-speak for "the numbers this function accepts."
math.pi
Let's start with a very simple and super helpful constant: pi, the famous circle number 3.14159... A constant is a value that never changes, so there are no parentheses. You don't call it, you just use it.
Without the math module, you would have to type pi's digits in by hand, or measure a circle's circumference and radius and divide. With the module, you just write math.pi:
import math print("The value of pi is: " + str(math.pi)) print("") radius = 3 area = round(math.pi * radius ** 2) circumference = round(2 * math.pi * radius) print("Area: " + str(area)) print("Circumference: " + str(circumference))
The value of pi is: 3.141592653589793 Area: 28 Circumference: 19
Pi playground
Here is that same circle math, live. Change the radius and watch math.pi do the work in both formulas:
Pi playground
math.pi * 3 ** 2 = 28.274333882308138
2 * math.pi * 3 = 18.84955592153876
area ≈ 28.27, circumference ≈ 18.85
math.e
The math module carries a second famous constant: Euler's number, e = 2.718... It shows up everywhere things grow or shrink at a steady rate: money earning interest, populations, probability, even nuclear physics!
Caffeine? Yes! The formula below models how 100mg of caffeine (about one cup of coffee) leaves the body after t hours. Try imagining different values of t to see how the amount left changes:
import math print("The value of e is: " + str(math.e)) print("") t = 5 # time in hours after consuming 100mg of caffeine caffeine_in_body = round(100 * math.e ** (-.17 * t)) print("After " + str(t) + " hours, there may be about " + str(caffeine_in_body) + "mg of caffeine left in the body.")
The value of e is: 2.718281828459045 After 5 hours, there may be about 43mg of caffeine left in the body.
Arithmetic functions
Beyond constants, the math module hangs a whole row of helpful arithmetic functions on the board. Here are five you'll reach for the most:
math.sqrt(number)returns the square root of a numbermath.fabs(number)returns the absolute value of a number (distance from zero, always positive)math.ceil(number)returns the smallest integer greater than or equal to a number (rounds UP)math.floor(number)returns the largest integer less than or equal to a number (rounds DOWN)math.gcd(number1, number2)returns the greatest common factor of two numbersCheck them out in action. Before you press Run, try predicting all five answers for 5.7:
import math number = 5.7 print("The number is: " + str(number)) print("") print("Using math.sqrt: " + str(math.sqrt(number))) print("Using math.ceil: " + str(math.ceil(number))) print("Using math.floor: " + str(math.floor(number))) print("Using math.fabs: " + str(math.fabs(number))) print("") print("---------------------------------") print("") number1 = 12 number2 = 8 print("The two numbers are: " + str(number1) + ", " + str(number2)) print("Using math.gcd: " + str(math.gcd(number1, number2)))
The number is: 5.7 Using math.sqrt: 2.3874672772626644 Using math.ceil: 6 Using math.floor: 5 Using math.fabs: 5.7 --------------------------------- The two numbers are: 12, 8 Using math.gcd: 4
Experiment: what happens when number is negative? math.fabs(-5.7) happily gives 5.7, but math.sqrt(-5.7) crashes with a math domain error. Scroll back up to the toolbox tester and try it!
Module functions vs built-in operators
Some jobs can be done two ways: with a plain Python operator you already know, or with a math module tool. Neither is "wrong," but they behave a little differently, so it pays to know both:
Powers: ** vs math.pow()
2 ** 3 gives 8 (an int)
math.pow(2, 3) gives 8.0 (always a float)
For everyday powers, ** is the go-to. It even handles square roots: 16 ** 0.5 is 4.0, though math.sqrt(16) says what you mean more clearly.
Absolute value: abs() vs math.fabs()
abs(-7) gives 7 (keeps the type)
math.fabs(-7) gives 7.0 (always a float)
The built-in abs() needs no import. math.fabs() is handy when you want a float no matter what. The "f" literally stands for float!
Rounding: round() vs ceil/floor
round(5.7) gives 6 (nearest integer)
math.ceil(5.2) gives 6, always UP
math.floor(5.9) gives 5, always DOWN
Use round() for "closest," and ceil/floor when the direction matters, like buses: 46 students, 20 seats each, you need math.ceil(46 / 20) = 3 buses, not 2!
Rule of thumb: operators and built-ins like **, abs(), and round() cover simple jobs with zero imports. The moment you need pi, square roots, ceil, floor, gcd, or trig, that's the math module's department.
Trigonometric functions
The math module also includes the common trig functions, the ones that connect angles to the sides of triangles. Without these pre-built tools, tons of real-life calculations (video game movement, GPS, building ramps) would be really hard to program:
math.sin(angle)returns the sine of the angle (angle given in radians)math.cos(angle)returns the cosine of the angle (in radians)math.tan(angle)returns the tangent of the angle (in radians)math.degrees(angle)converts an angle from radians to degreesmath.radians(angle)converts an angle from degrees to radiansHaven't met sine and cosine in math class yet? No problem, just remember the big idea: these functions expect radians, a different unit for measuring angles, and the module gives you converters both ways. Here they all are with a right triangle that has a 60 degree angle and a hypotenuse (longest side) of 5:
import math angleR = math.pi / 2 angleD = math.degrees(angleR) print("Right angle in radians: " + str(angleR)) print("Right angle in degrees: " + str(angleD)) print("") # right triangle calculations angle = math.radians(60) hypotenuse = 5 adjacent = round(hypotenuse * math.cos(angle), 2) opposite = round(hypotenuse * math.sin(angle), 2) print("The adjacent side of the right triangle is " + str(adjacent)) print("The opposite side of the right triangle is " + str(opposite))
Right angle in radians: 1.5707963267948966 Right angle in degrees: 90.0 The adjacent side of the right triangle is 2.5 The opposite side of the right triangle is 4.33
There's even more: the math module also has tools for exponents, logarithms, and beyond. The full list lives in the official Python math module documentation.
Practice problems
Time to build something with the tools. Open your favorite Python editor (or a CodeHS sandbox), start with import math, and try these:
Circle stats
Write a program that calculates and prints the area and circumference of a circle with radius 12. Round both answers to 2 decimal places with round(value, 2).
import math radius = 12 area = round(math.pi * radius ** 2, 2) circumference = round(2 * math.pi * radius, 2) print("Area: " + str(area)) print("Circumference: " + str(circumference))
Area: 452.39 Circumference: 75.4
Fun check: the circumference rounded to 75.4, not 75.40. Python trims trailing zeros when it prints floats.
Triangle detective
A right triangle has a hypotenuse of length 10 and an adjacent side of length 6. Calculate the angle between them, in degrees.
Extra challenge: also calculate the length of the unknown third side and the final unknown angle (in degrees).
- Cosine of the angle = adjacent / hypotenuse. The math module's math.acos() (arc cosine) works in reverse: give it adjacent / hypotenuse and it gives you the angle back, in radians.
- Remember the converter: math.degrees() turns radians into degrees.
- For the third side, the Pythagorean theorem plus math.sqrt() is all you need.
- The three angles of any triangle add up to 180 degrees, and one of them here is 90.
import math hypotenuse = 10 adjacent = 6 # acos reverses cosine: it turns adjacent / hypotenuse back into the angle angle = math.degrees(math.acos(adjacent / hypotenuse)) print("Angle: " + str(round(angle, 2)) + " degrees") # Pythagorean theorem for the third side opposite = math.sqrt(hypotenuse ** 2 - adjacent ** 2) print("Opposite side: " + str(opposite)) # The angles add up to 180, and the right angle takes 90 other_angle = 90 - angle print("Other angle: " + str(round(other_angle, 2)) + " degrees")
Angle: 53.13 degrees Opposite side: 8.0 Other angle: 36.87 degrees
Nice and tidy: the third side came out to exactly 8.0. A 6-8-10 triangle is a scaled-up 3-4-5 right triangle, one of the most famous triangles in math!
Quick quiz
1. What must a program include before it can use math.sqrt()?
2. Which of these returns 8 when given 7.3?
3. What does print(math.sqrt(25)) output?
Keep learning Python
Your toolbox is stocked. Brush up on the basic operators the module builds on, or put your new functions to work generating random numbers for games.