The math Module
Use the built-in math module for advanced calculations.
Syntax
import math
math.sqrt(x)For maths beyond the basic operators, Python's standard library includes the math module. Import it, then use its functions and constants.
math.sqrt(x)— square root.math.floor(x)/math.ceil(x)— round down / up.math.pi,math.e— constants.
The round() function is built in and needs no import.
Example
import math
print(math.sqrt(144))
print(math.floor(4.9))
print(math.ceil(4.1))
print(round(math.pi, 2))
# Output:
# 12.0
# 4
# 5
# 3.14When to use it
- A geometry app uses math.sqrt() and math.pi to compute the circumference of a circle.
- A financial model rounds up a loan payment with math.ceil() to avoid undercharging.
- A game engine uses math.degrees() to convert radian angles returned by trigonometric functions.
More examples
Common math functions
Shows frequently used math functions for roots, powers, and rounding.
import math
print(math.sqrt(144)) # 12.0
print(math.pow(2, 10)) # 1024.0
print(math.floor(4.7)) # 4
print(math.ceil(4.2)) # 5
print(round(3.14159, 2)) # 3.14Pi and trigonometry
Uses math.pi and trigonometric functions with radians conversion for geometry.
import math
radius = 7
circumference = 2 * math.pi * radius
print(f'{circumference:.2f}') # 43.98
angle_deg = 45
angle_rad = math.radians(angle_deg)
print(f'sin(45deg) = {math.sin(angle_rad):.4f}') # 0.7071Logarithm and constants
Demonstrates logarithms in different bases and the math module's special constants.
import math
print(math.log(100, 10)) # 2.0 (log base 10)
print(math.log2(256)) # 8.0
print(math.e) # 2.718...
print(math.inf > 10**9) # True
Discussion