NameError: name 'nan' is not defined in Python

Borislav Hadzhiev

Last updated: Apr 20, 2022

Photo from Unsplash

**The Python "NameError: name 'nan' is not defined" occurs when we use the nan
variable from numpy without importing it. To solve the error, make sure to
install numpy and import nan (from numpy import nan).**

Open your terminal in your project's root directory and install the `numpy`

module.

shell

`# 👇️ in a virtual environment or using Python 2 pip install numpy # 👇️ for python 3 (could also be pip3.10 depending on your version) pip3 install numpy # 👇️ if you get permissions error sudo pip3 install numpy # 👇️ if you don't have pip in your PATH environment variable python -m pip install numpy # 👇️ for python 3 (could also be pip3.10 depending on your version) python3 -m pip install numpy # 👇️ for Anaconda conda install -c anaconda numpy`

After installing numpy, you can import the
`nan`

variable.

main.py

`from numpy import nan, log print(nan) print(log([-1, 1, 2])) # array([ NaN, 0. , 0.69314718])`

The import statement shows how to import `nan`

and `log`

from `numpy`

.

The `nan`

variable returns a floating point representation of Not a Number.

Note that `NaN`

and `NAN`

are aliases of `nan`

.

Alternatively, you can import the entire `numpy`

module and access `nan`

as a
property.

main.py

`import numpy as np print(np.nan) print(np.log([-1, 1, 2])) # array([ NaN, 0. , 0.69314718])`

We imported the entire `numpy`

module and aliased it to `np`

, so you would
access the `nan`

variable as `np.nan`

.

Make sure you haven't used a capital letter

`n`

when importing `numpy`

because module names are case-sensitive.Also, make sure you haven't imported `numpy`

in a nested scope, e.g. a function.
Import the module at the top level to be able to use it throughout your code.

**The Python "NameError: name 'nan' is not defined" occurs when we use the nan
variable from numpy without importing it. To solve the error, make sure to
install numpy and import nan (from numpy import nan).**