You import the math module by putting import math at the top of your script, then calling its functions with a math. prefix, for example math.sqrt(16) returns 4.0. That single line gives you Python's built-in library of mathematical functions: square roots, trigonometry, logarithms, rounding helpers and constants such as pi and e. It is part of the standard library, so there is nothing to install and no separate package to download, as long as you already have Python itself working on your machine.
What You'll Need
- A working Python installation (version 3.x is the norm everywhere now), which you can confirm by running
python --versionorpython3 --versionin a terminal. - Somewhere to write and run code: a script file with
.pyextension, or any REPL such as IDLE, a terminal session, or a notebook. - A basic understanding of calling functions and of how modules are referenced, though the steps below cover the essentials.
- No internet connection is required:
mathships with Python, so it works offline and on locked-down machines.
Step-by-Step
- Open your file or interpreter. Create a new file called something like
example.py, or launch a Python REPL by typingpythonorpython3in a terminal. Both work identically for importing modules; the REPL just runs each line as you press Enter. - Put the import at the top. On the first line of the file, write
import math. By convention imports go at the top of the file, before any other code, so anyone reading the script can see its dependencies immediately. Python does not require that position, but it is the standard style and worth keeping. - Run the file or press Enter in the REPL. If nothing appears, the import succeeded. Python only raises an error at import time if the module name is wrong or the module is missing from the installation.
- Call a function with the
math.prefix. Add a line such asprint(math.sqrt(25))and run it. You should see5.0. The prefix is not optional with a plainimport math: writingsqrt(25)on its own raisesNameError: name 'sqrt' is not defined. - Try the constants.
math.pigives you pi to the precision Python stores, andmath.egives Euler's number. Note there are no parentheses after constants, because they are values, not functions:
Putting the first few steps together, a working script looks like this:
import math
radius = 3
area = math.pi * radius ** 2
hypotenuse = math.sqrt(3 ** 2 + 4 ** 2)
print(area)
print(hypotenuse)
Running it prints the area of a circle with radius 3 and then 5.0.
- Decide whether to import the whole module or specific names.
import mathkeeps every function namespaced undermath, which is the clearest option and what most code uses.from math import sqrt, pipulls individual names into your script so you can writesqrt(25)directly. Use the second form sparingly, because bare names likepican collide with your own variables and make code harder to follow. - Give the module a shorter alias if you prefer.
import math as mlets you writem.sqrt(25). This is legal Python but unusual for themathmodule; short aliases matter more for long third-party package names. - Look up what is available. In a REPL, run
dir(math)to print a list of every name the module provides. For a description of one function, usehelp(math.sqrt)orhelp(math)for the whole module. This is the fastest way to check whether a particular function exists rather than guessing. - Pick the right function for the job. Common ones worth knowing:
math.sqrtfor square roots,math.powfor powers,math.floorandmath.ceilfor rounding down and up,math.factorialfor factorials,math.logfor natural logarithms,math.log10for base-10 logarithms, andmath.sin,math.cos,math.tanfor trigonometry. The trigonometric functions take angles in radians, not degrees, so convert first withmath.radians(45). - Handle the errors the functions can raise. Functions check their inputs.
math.sqrt(-1)raisesValueError: math domain error, andmath.log(0)does the same. If your input comes from user data or a calculation, validate it before calling, or wrap the call in atry/except ValueErrorblock and supply a sensible fallback. - Keep working in the REPL or rerun the script. When you change a script, save it and run it again. Inside a REPL, a module already imported stays as it was until you restart the session, which matters if you are debugging.
Common Mistakes
- Forgetting the prefix. Writing
sqrt(16)afterimport mathfails with aNameError. Either usemath.sqrt(16)or import the name explicitly. - Naming your own file
math.py. Python searches the folder containing your script before the standard library, so a file with that name shadows the real module and produces confusing errors about missing functions. Rename your file and delete any leftovermath.pycin the same folder. - Using degrees with trigonometric functions.
math.sin(90)does not return1.0; it treats 90 as radians. Convert withmath.radiansormath.degreesas appropriate. - Expecting integers.
math.sqrt(16)returns4.0, a float, not4. Mostmathfunctions return floats, which is fine for printing but can matter for exact comparisons and for indexing. - Calling constants as functions.
math.pi()raisesTypeErrorbecausepiis a value. Drop the parentheses. - Using
^for powers. The caret is bitwise XOR in Python, not exponentiation. Use**ormath.pow.
Tips
- Reach for
mathwhen you want plain numbers back. When you need arrays for many values at once, NumPy is the usual choice;mathworks one value at a time. math.isclose(a, b)is a safer way to compare floating-point results than==, because rounding makes exact equality unreliable.- Some names also exist as built-ins, such as
round,absandmin, so you do not need the module for those.math.floorandmath.ceilhave no built-in equivalent. - For very large integers, Python's own
**operator handles arbitrary sizes, whilemath.powconverts to floats and can overflow. - Keep the import list alphabetical and grouped at the top;
mathsits with the standard-library imports, before any installed packages.
Troubleshooting
ModuleNotFoundErrororImportErroronimport math: this points to a broken or unusual Python installation rather than your code, sincemathis part of the standard library. Check that you are running the interpreter you expect (some systems have several), and look for a file or folder in your working directory namedmath.pyormaththat is shadowing it. If the installation itself is damaged, reinstall Python from the official source.NameErrorfor a function: you either called it without themath.prefix or imported it with a different alias. Check how you imported at the top of the file.ValueError: math domain error: the function received a value it cannot handle, such as a negative square root or the logarithm of zero. Inspect the input just before the call, for example by printing it.TypeErrorabout the number of arguments: you have called a function with the wrong count, or treated a constant as a function. Callhelp(math.name)in the REPL to see the expected signature.- The result looks wrong but nothing errors: check the unit. Degrees-versus-radians and integer-versus-float confusion account for most surprising results.
- Changes to a script do not appear: you may be running a different file path or an open REPL session that still holds the old code. Restart the interpreter and run the saved file again.
Frequently Asked Questions
Do I need to install anything to use math in Python?
No. math is part of the Python standard library and comes with every normal installation. It works offline and needs no package manager.
What is the difference between import math and from math import sqrt?
import math loads the module and you reach names through the math. prefix. from math import sqrt copies just that name into your script so you can call it directly. The first is clearer in larger programs.
Why does math.sqrt return a decimal instead of a whole number?
Most math functions return floats by design. If you need an integer, convert explicitly, for example with int(math.sqrt(16)), but be aware that conversion truncates rather than rounds.
Does the math module work with complex numbers?
No. Functions like math.sqrt raise an error for negative inputs. Use the separate cmath module when you need complex-number results.
How do I find all the functions in the math module?
Run dir(math) in a REPL to list the names, or help(math) to read a summary of each one. The official Python documentation also lists them all.
Can I rename the module when I import it?
Yes, with import math as m, after which you write m.pi and m.sqrt(). It is allowed but uncommon for a short name like math.