Python Math

Python offers built-in math functions plus a math module that unlocks more advanced mathematical operations.

Built-in math functions

Some mathematical work needs no imports at all. Python always makes a handful of numeric functions available, including min() and max() to find the smallest or largest value, abs() for the absolute value, and pow() or the ** operator to raise a number to a power.

Using the always-available functions

print(min(5, 12, 3))   # 3
print(max(5, 12, 3))   # 12
print(abs(-7.4))       # 7.4
print(pow(2, 5))       # 32  (same as 2 ** 5)
print(round(3.14159, 2)) # 3.14

The math module

For anything beyond the basics, import the math module. It provides functions for square roots, rounding in a specific direction, trigonometry, factorials, and useful constants such as pi and the mathematical constant e.

Common math module functions

import math

print(math.sqrt(64))    # 8.0
print(math.ceil(4.1))   # 5  (rounds up)
print(math.floor(4.9))  # 4  (rounds down)
print(math.factorial(5))# 120
print(math.pi)          # 3.141592653589793
  • math.ceil(x) rounds a number up to the nearest whole number.
  • math.floor(x) rounds a number down to the nearest whole number.
  • math.sqrt(x) returns the square root as a float.
  • math.pow(x, y) returns x raised to the power y as a float.
  • math.gcd(a, b) returns the greatest common divisor of two integers.
Note: math.floor() and math.ceil() always return an int, while the built-in round() may return a float. Also note that round() uses banker's rounding, so round(2.5) gives 2, not 3.
FunctionPurposeExample result
math.sqrt(x)Square rootmath.sqrt(25) -> 5.0
math.ceil(x)Round upmath.ceil(2.2) -> 3
math.floor(x)Round downmath.floor(2.9) -> 2
math.factorial(x)Factorialmath.factorial(4) -> 24
math.piConstant pi3.141592653589793

Trigonometry and logarithms

import math

# Trig functions expect radians
angle = math.radians(90)
print(round(math.sin(angle), 2))  # 1.0

print(math.log(math.e))    # 1.0 (natural log)
print(math.log10(1000))    # 3.0

Exercise: Python Math

What happens when you call `math.sqrt(x)` with a negative value of x?