NameError: name 'math' is not defined in Python

Borislav Hadzhiev

Last updated: Apr 20, 2022

Photo from Unsplash

**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 math
module before using it - import math.**

Here is an example of how the error occurs.

main.py

`# ⛔️ 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.

main.py

`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.

Make sure you haven't used a capital letter

`m`

when importing `math`

because 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.

main.py

`from math import ceil, floor print(ceil(1.2)) # 👉️ 2 print(floor(1.7)) # 👉️ 1`

The example shows how to import the `ceil()`

and `floor()`

functions from the
`math`

module.

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.**

For example, when we use an import such as

`import math`

, it is much harder to see which functions from the `math`

module 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.

The `math`

module provides access to many mathematical functions that are
defined by the C standard.

The `math`

module also provides some commonly used constants, e.g. `pi`

.

main.py

`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.

**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 math
module before using it - import math.**