This error occurs when Python can't find the module you're trying to import. The package either isn't installed, is installed in a different Python environment, or you have a typo in the import statement.
The "ModuleNotFoundError: No module named 'X'" error means Python looked for a module called 'X' but couldn't find it. This happens when: 1. The package isn't installed in your current Python environment 2. You're using the wrong Python interpreter (python vs python3) 3. The package is installed globally but you're using a virtual environment 4. You have a typo in the import statement or module name 5. The package has a different import name than its installation name (e.g., install 'pillow', import 'PIL') The solution is to install the missing package using `pip install` in the correct Python environment.
Check which Python your script is using:
which python3
python3 --versionAlways use python3 explicitly to avoid Python 2.
List installed packages:
pip list
# or
pip3 listSearch for your package:
pip show package-nameInstall using pip (check PyPI for correct package name):
pip install package-name
# or
pip3 install package-nameFor example, to import PIL, install pillow:
pip install pillowCreate and activate a virtual environment to isolate dependencies:
python3 -m venv myenv
source myenv/bin/activate # On Linux/Mac
myenv\\Scripts\\activate # On Windows
pip install package-nameVerify your import statement is correct:
# Correct
import numpy
from pandas import DataFrame
# Incorrect
import numpy as np # This works but imports 'numpy' package
import nump # Typo - package name is 'numpy'Some packages have different import names than package names (e.g., install 'Pillow' but import 'PIL', install 'pyyaml' but import 'yaml'). Check PyPI documentation for the correct import name.
ValueError: math domain error
How to fix "ValueError: math domain error" in Python
ERROR: Could not install packages due to an OSError: [Errno 13] Permission denied: '/usr/lib/python3/dist-packages'
How to fix "Permission denied" when installing packages with pip
ERROR: Could not install packages due to an OSError: [Errno 30] Read-only file system: '/usr/lib/python3/dist-packages'
How to fix "Read-only file system" error when installing packages with pip
socket.gaierror: [Errno -2] Name or service not known
How to fix "socket.gaierror: [Errno -2] Name or service not kn" in Python
pydantic_core._pydantic_core.ValidationError: 1 validation error
How to fix "pydantic_core._pydantic_core.ValidationError: 1 va" in Python