NameError: name 'scipy' is not defined in Python

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

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

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

nameerror name scipy is not defined

Open your terminal in your project's root directory and install the scipy module.

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

After you install the scipy module, make sure to import it before using it.

main.py
import scipy.integrate import scipy.special result = scipy.integrate.quad( lambda x: scipy.special.jv(2.5, x), 0, 4.5 ) print(result)

The example shows how to import the scipy.integrate and scipy.special sub-modules.

Alternatively, you can import the sub-modules from scipy to not have to prefix every interaction with scipy..

main.py
from scipy import integrate, special, stats result = integrate.quad(lambda x: special.jv(2.5, x), 0, 4.5) print(result) print(stats.norm.cdf(0))

Instead of accessing each sub-module as scipy.sub_module, we now access the sub-modules directly.

You can also import only the functions you intend to use from each module.

main.py
from scipy.integrate import quad from scipy.special import jv from scipy.stats import norm result = quad(lambda x: jv(2.5, x), 0, 4.5) print(result) print(norm.cdf(0))

Whichever approach you pick make sure you have imported the members you are accessing, otherwise the "Name 'X' is not defined" error occurs.

Conclusion #

The Python "NameError: name 'scipy' is not defined" occurs when we use the scipy module without importing it first. To solve the error, install the scipy module and import it 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.