Wed Apr 20 2022·2 min read
Photo by Raychan
The Python "NameError: name 'math' is not defined" occurs when we use the
math module without importing it first. To solve the error, import the
module before using it -
Here is an example of how the error occurs.
# ⛔️ NameError: name 'math' is not defined print(math.ceil(1.2)) print(math.floor(1.7))
To solve the error, we have to import the math module.
import math print(math.ceil(1.2)) # 👉️ 2 print(math.floor(1.7)) # 👉️ 1
Even though the
math module is in the Python standard library, we still have
to import it before using it.
mathbecause module names are case-sensitive.
Alternatively, you can make your code a little more concise by only importing the functions that you use in your code.
from math import ceil, floor print(ceil(1.2)) # 👉️ 2 print(floor(1.7)) # 👉️ 1
The example shows how to import the
floor() functions from the
Instead of accessing the functions on the module, e.g.
math.floor(), we now
access them directly.
This should be your preferred approach because it makes your code easier to read.
import math, it is much harder to see which functions from the
mathmodule are being used in the file.
Conversely, when we import specific functions, it is much easier to see which
functions from the
math module are being used.
math module provides access to many mathematical functions that are
defined by the C standard.
math module also provides some commonly used constants, e.g.
from math import pi print(pi) # 👉️ 3.141592653589793
You can view all of the functions and constants the
math module provides by
visiting the official docs.