Python Modules & Packages
Python math Module
The math module is Python's built-in toolbox of mathematical functions and constants, going far beyond the basic + - * / operators.
Importing math
Since math ships with the standard library, no installation is needed — just import it at the top of your file to unlock dozens of mathematical functions and constants.
import mathSquare Roots and Powers
math.sqrt() calculates a square root, while math.pow() raises a number to a given power. Note that math.pow() always returns a float, unlike the ** operator, which keeps integers as integers.
print(math.sqrt(64))
print(math.pow(2, 5))Rounding Down and Up
math.floor() rounds a number down to the nearest whole number, and math.ceil() rounds it up — both are more precise than round(), which rounds to the nearest value.
print(math.floor(4.7))
print(math.ceil(4.2))Useful Constants
The module also stores well-known mathematical constants so you never have to type long decimal approximations yourself.
print(math.pi)
print(math.e)Factorial
math.factorial() multiplies a number by every positive whole number below it, commonly used in probability and combinatorics problems.
print(math.factorial(5))| Function / Constant | Purpose | Example |
|---|---|---|
| math.sqrt(x) | Square root | math.sqrt(9) → 3.0 |
| math.pow(x, y) | x raised to power y | math.pow(2, 3) → 8.0 |
| math.floor(x) | Round down | math.floor(4.9) → 4 |
| math.ceil(x) | Round up | math.ceil(4.1) → 5 |
| math.pi | Value of pi | 3.14159... |
| math.e | Euler's number | 2.71828... |
| math.factorial(x) | x! | math.factorial(4) → 24 |
For most everyday exponent math you can also use the ** operator, like 2 ** 5, which keeps integer results as integers instead of floats.
