How to Import math in Python (and Use It)

Here’s how to import math in Python: write import math at the top of your file, then call functions with the math. prefix, like math.sqrt(16). The math module ships with Python, so there’s nothing to install:

import math
math.sqrt(16)    # 4.0
math.pi          # 3.141592653589793

I ran every snippet with Python 3.12.5 and copied the output exactly, including the errors.

You’ll see the three ways to import, the constants, the functions people use most, the errors you’ll run into, and when NumPy is the better choice.

Three ways to import math in Python

Without an import, Python doesn’t know sqrt. Pick one of three styles; all of them load the same module:

try:
    print(sqrt(16))
except NameError as err:
    print("NameError:", err)

import math
print("import math:          ", math.sqrt(16))

from math import sqrt, pi
print("from math import sqrt:", sqrt(16), "| pi =", pi)

import math as m
print("import math as m:     ", m.sqrt(16))

Output:

NameError: name 'sqrt' is not defined
import math:           4.0
from math import sqrt: 4.0 | pi = 3.141592653589793
import math as m:      4.0
Command Prompt output of a NameError for sqrt without importing, then import math, from math import sqrt and import math as m
The NameError disappears as soon as you import. All three styles return the same value.
StyleHow you call itWhen I use it
import mathmath.sqrt(x)Most of the time; it’s clear where each name comes from
from math import sqrt, pisqrt(x)Formula-heavy code using a few functions
import math as mm.sqrt(x)Rarely; the full name is already short

Avoid from math import *; it dumps dozens of names into your file and hides where they came from. More on imports in Python import from another directory.

Math constants: pi, e, tau and infinity

The module includes the constants you’d expect, at full float precision:

import math

radius = 3.5
print(f"pi    = {math.pi}")
print(f"e     = {math.e}")
print(f"tau   = {math.tau}")
print(f"inf   = {math.inf}, nan = {math.nan}")
print(f"circle area (r = {radius}): {math.pi * radius ** 2:.2f} sq ft")

Output:

pi    = 3.141592653589793
e     = 2.718281828459045
tau   = 6.283185307179586
inf   = inf, nan = nan
circle area (r = 3.5): 38.48 sq ft

Common math module functions

I find these cover most everyday needs: roots and powers, rounding, logarithms, factorials, trigonometry in radians, and safe float comparison:

import math

print("sqrt(144)       ", math.sqrt(144))
print("pow(2, 10)      ", math.pow(2, 10), "| 2 ** 10 =", 2 ** 10)
print("ceil(4.2)       ", math.ceil(4.2), "| floor(4.8):", math.floor(4.8), "| trunc(-4.8):", math.trunc(-4.8))
print("log(100, 10)    ", math.log(100, 10), "| log10(1000):", math.log10(1000), "| log2(8):", math.log2(8))
print("factorial(5)    ", math.factorial(5))
print("gcd(84, 126)    ", math.gcd(84, 126), "| lcm(4, 6):", math.lcm(4, 6))
print("sin(90 degrees) ", math.sin(math.radians(90)))
print("hypot(3, 4)     ", math.hypot(3, 4))
print("isclose(0.1+0.2, 0.3)", math.isclose(0.1 + 0.2, 0.3))

Output:

sqrt(144)        12.0
pow(2, 10)       1024.0 | 2 ** 10 = 1024
ceil(4.2)        5 | floor(4.8): 4 | trunc(-4.8): -4
log(100, 10)     2.0 | log10(1000): 3.0 | log2(8): 3.0
factorial(5)     120
gcd(84, 126)     42 | lcm(4, 6): 12
sin(90 degrees)  1.0
hypot(3, 4)      5.0
isclose(0.1+0.2, 0.3) True
Command Prompt output of common Python math module functions including sqrt, pow, ceil, floor, log, factorial, gcd, sin and isclose
Trig functions take radians, so convert degrees with math.radians() first.

math.isclose() is the right way to compare floats, since 0.1 + 0.2 == 0.3 is False. Some of these have their own guides: GCD in Python and exponents in Python.

Why do I get ValueError: math domain error?

You asked for something undefined for real numbers, such as the square root of a negative number or the log of zero. Use cmath for complex results:

import math
import cmath

try:
    math.sqrt(-9)
except ValueError as err:
    print("ValueError:", err)

print("cmath.sqrt(-9):", cmath.sqrt(-9))          # complex numbers live in cmath

try:
    math.log(0)
except ValueError as err:
    print("ValueError:", err)

import numpy as np
prices = np.array([4.0, 9.0, 16.0])
try:
    math.sqrt(prices)
except TypeError as err:
    print("TypeError:", err)
print("np.sqrt works on arrays:", np.sqrt(prices))

Output:

ValueError: math domain error
cmath.sqrt(-9): 3j
ValueError: math domain error
TypeError: only 0-dimensional arrays can be converted to Python scalars
np.sqrt works on arrays: [2. 3. 4.]
Command Prompt output of Python math domain errors for sqrt of a negative and log of zero, cmath sqrt, and a TypeError on a NumPy array
math works on single numbers. For whole arrays, use NumPy’s versions instead.

There’s a dedicated guide to ValueError: math domain error. And if you pass a NumPy array, use np.sqrt and friends, which work element by element.

Handy newer math functions

Recent Python versions added several functions that save writing loops by hand:

import math

boxes = [3, 4, 5]
print("prod:", math.prod(boxes))                              # multiply everything (3.8+)
print("isqrt(50):", math.isqrt(50))                           # exact integer square root
print("dist:", math.dist((0, 0), (3, 4)))                     # distance between points
print("comb(10, 3):", math.comb(10, 3), "| perm(10, 3):", math.perm(10, 3))
total = 0.0
for x in [0.1] * 10:
    total += x                                               # plain loop: rounding errors add up
print("loop:", total, "| fsum:", math.fsum([0.1] * 10))

Output:

prod: 60
isqrt(50): 7
dist: 5.0
comb(10, 3): 120 | perm(10, 3): 720
loop: 0.9999999999999999 | fsum: 1.0

A plain loop that adds 0.1 ten times ends at 0.9999999999999999, while math.fsum() tracks the rounding error and gives 1.0. (Since Python 3.12, the built-in sum() of floats is more accurate too.)

math vs numpy vs cmath

ModuleWorks onUse it for
mathSingle int and float valuesEveryday calculations
cmathComplex numbersRoots of negatives, signal math
numpyWhole arrays at onceData, matrices, large calculations

More Python math tutorials you might like:

Frequently asked questions

How do I import math in Python?

Add import math at the top of your file and use functions as math.sqrt(), math.pi and so on.

Do I need to install the math module?

No. It’s part of Python’s standard library and is always available.

What’s the difference between import math and from math import *?

import math keeps names under the math. prefix. from math import * copies them all into your file, which can clash with your own names.

Why does math.sqrt give a math domain error?

The input is negative. Use cmath.sqrt() for a complex result or check the value first.

Can I use math functions on a list or array?

Not directly. Loop over the list, or use NumPy functions like np.sqrt() on arrays.

Where is the math module documented?

See math in the Python docs.