NameError: name 'numpy' is not defined in Python

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

NameError: name 'numpy' is not defined in Python #

The Python "NameError: name 'numpy' 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) before using it.

nameerror name numpy is not defined

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

main.py
# ✅ import numpy first import numpy print(numpy.arange(6)) print(numpy.array([1, 2, 3, 4, 5])) print(numpy.zeros(2))
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.

Note that the numpy module is often aliased to np in import statements.

main.py
import numpy as np print(np.arange(6)) print(np.array([1, 2, 3, 4, 5])) print(np.zeros(2))

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.

Conclusion #

The Python "NameError: name 'numpy' 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) before using it.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.