Borislav Hadzhiev
Wed Apr 20 2022·2 min read
Photo by Raychan
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.
Open your terminal in your project's root directory and install the scipy
module.
# 👇️ 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.
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.
.
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.
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.