NameError: name 'np' is not defined in Python

Borislav Hadzhiev

Last updated: Apr 20, 2022

Photo from Unsplash

**The Python "NameError: name 'np' is not defined" occurs when we use the
numpy module without importing it first. To solve the error, install the
module and import it (import numpy as np) before using it.**

Open your terminal in your project's root directory and make sure you have the
`numpy`

module installed.

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 you install the numpy module, import it before using it.

main.py

`# ✅ import numpy and alias it as np import numpy as np print(np.arange(5)) print(np.array([1, 2, 3, 4, 5])) print(np.zeros(5))`

The import statement imports the `numpy`

module and aliases it to `np`

, so we
access the module's classes as `np.array`

, `np.zeros`

, etc.

Make sure you haven't misspelled `numpy`

and are using all lowercase letters
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 'np' is not defined" occurs when we use the
numpy module without importing it first. To solve the error, install the
module and import it (import numpy as np) before using it.**