[Fixed] ModuleNotFoundError: No module named ‘numpy’

Summary: The most common cause of ModuleNotFoundError is a faulty installation of the module or importing a module incorrectly. For a successful installation of the module, use pip3 install numpy.

◈ Overview

If you are someone like me who works with lots and lots of data, then Import Error: No module named 'xyz' is probably one of the most common errors that you have come across. In this article, I will discuss the causes and solutions to this error in Python.

Example: Suppose that you are trying to import the Numpy library and print an array. However you get an ImportError: ModuleNotFoundError: No module named 'numpy'.

Output:

➥ Reasons of Import Error: No module Named ‘xyz’

Two major reasons that lead to the occurrence of this error:

  • You have not installed the module correctly, i.e., you are using an older version of the module, which is not compatible with the version of Python you are using.
  •  The Python-version/environment where you installed the package is not the same.
    • Note: This usually happens when you have two versions of Python (Python 2.x and Python 3.x simultaneously) installed on your system.

◈ Solution

Let us dive into the probable solutions to our problem.

❋ Method 1: Fixing Faulty Installation

If you are on Python version 3, then you must install the latest version of the package. In our case, we must install the latest version of Numpy. Before we dive into the commands to install the latest version of Numpy, let us look at the following visual, which explains what happens when you try to install an older version of Numpy on Python 3.

Thus, it is clear from the above example that even though you installed Numpy, the ModuleNotFoundError was not resolved. The reason is you installed an older version of Numpy ,which is incompatible with Python 3.

Note:

  • The command to install a particular version of Numpy is:- pip install numpy==x.y.z
    • Here x.y.z re[resents the version of Numpy you want to install, for example:- numpy==1.8.2

To resolve this issue, you can use the following command in your terminal to ensure that the latest version of Numpy is installed:

pip3 install numpy

Let’s have a look at the following graphic to visualize the solution.

❋ Method 2: Fixing Missing Path

Sometimes, even the above procedure does not work. Whenever you import a module, python searches the module in specific directories.

To get hold of all the directories that Python will search, you can use piece of code:

Output:

Disclaimer: The paths shown in this output will vary from user to user.

D:\PycharmProjects\pythonProject1
D:\PycharmProjects\pythonProject1
C:\Program Files (x86)\Python38-32\python38.zip
C:\Program Files (x86)\Python38-32\DLLs
C:\Program Files (x86)\Python38-32\lib
C:\Program Files (x86)\Python38-32
C:\Users\DELL\AppData\Roaming\Python\Python38\site-packages
C:\Program Files (x86)\Python38-32\lib\site-packages

You should make sure that the NumPy module resides in any of these directories. Once a module has been imported, you can find its location with the help of the module’s __file__ attribute:

Output:

Disclaimer: The paths shown in this output will vary from user to user.

C:\Users\DELL\AppData\Roaming\Python\Python38\site-packages\numpy\__init__.py

If the NumPy module is not found in any of the listed directories, then you have to append it to the python search path using the following statements:

You also have other options to ensure that your module is found. These are:

  • Put module.py inside the directory containing the input script.
  • Modify the environment variable: PYTHONPATH and ensure that it contains the directory where module.py is located before you start the interpreter.
    • You can also opt to put mod.py in one of the directories already present in the PYTHONPATH environment variable.

In case you are struggling with this error despite following all the above methods, and you are using Jupyter Notebook, then you might want to have a look at this article.

◈ Scenario 2: ModuleNotFoundError In Case Of User-Defined Modules

Previously we found out how to resolve the ModuleNotFoundError when we are dealing with in-built modules/packages. If you are working with user-defined modules, you may still encounter this problem.

Example: Consider that you have created a user- defined module ex. This module is within a directory named UserDefinedModule.

Now you want to import this module into your program as shown below:

Output:

Explanation:

The module ex is not a part of the current working directory. Therefore, Python is unable to import the required module successfully.

Solutions:

  • The first solution is to make sure that the module being imported and the program that imports the module are in the same directory.
  • The second way of avoiding this error is to import the module from its relative path as shown in the illustration given below.

Explanation:

Since the ex module is contained within the UserDefinedModule directory, so you must import it from this folder itself using the import statement: from UserDefinedModule import ex

Conclusion

In this article, you learned how to avoid the ModuleNotFoundError in Python.

  • While working with an external module, make sure you have installed it properly.
  • While working with a user-defined module, you must use your import statements properly and ensure that the modules are imported from their relative paths.

Please subscribe and stay tuned for exciting articles. Happy learning! 📚


import_contacts

You may also like:

Related Posts

  • Convert dict to String in Python
    17 December

    Convert dict to string in python

    Table of ContentsHow to convert dict to string in python?Using str() method.Using the pickle module.Using the for loop.Using the json.dumps() method. In this post, we will see how to convert dict to String in Python. Python contains several data structures, and more often than not, there is a need for the conversion of one type […]

  • Python range float
    17 December

    Generate float range in Python [9 ways]

    Table of ContentsWhat is a floating-point number in Python?Why not use the simple and popular range() function?Python range float : How to generate floating-point numbers in Python?Using the numpy.linspace() method.Using the numpy.arange() method.Using list comprehension.Using generator comprehension.Using yield generator.Using a user-defined function.Using the itertools module and its functions.Using the map() function along with a lambda […]

  • Python callback function
    13 December

    Callback function in Python

    Table of ContentsWhat is Callback Function in Python?Applications of Callback Functions in PythonConclusion In python, functions are first-class objects. In other words, we can pass a function to a different function as an input argument. We can return a function from another function, and we can assign a function to a variable. In this article, […]

  • ValueError: too many values to unpack
    10 December

    [Fixed] ValueError: too many values to unpack (expected 2)

    Table of ContentsWhat is unpacking in python?What is ValueError: too many values to unpack (expected 2)?How to resolve ValueError: too many values to unpack (expected 2)?Conclusion While programming in python, we can assign values to two or more variables in a single statement. While doing so, you might get the ValueError exception with the message […]

  • Python List of dictionaries
    09 December

    List of Dictionaries in Python

    Table of ContentsHow to Create a List of Dictionaries in Python?How to Access Elements of a List of Dictionaries?Search in a List of Dictionaries in PythonUpdate Values in a List of Dictionaries in PythonHow to Sort List of Dictionaries in Python?Conclusion We use both lists and dictionaries in our python programs. Lists are used to […]

  • Python if not
    08 December

    Python If with NOT Operator

    Table of ContentsNOT Operator and IF Statement in PythonApplications of the if statement with not operator in pythonConclusion In python, we use conditional statements to implement logic in our program. For this, we use boolean expressions with if statements. In this article, we will see how we can use the if statement with the not […]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.