Python Tutorial
Python Flow Control
Python Functions
Python Data Types
Python Date and Time
Python Files
Python String
Python List
Python Dictionary
Python Variable
Python Input/Output
Python Exceptions
Python Advanced
ImportError
and ModuleNotFoundError
are two common exceptions that occur when there's an issue with importing modules or their components in Python.
ImportError
is raised when the interpreter cannot find a module or an object (such as a class, function, or variable) within a module. This can happen if the module or object is misspelled, not installed, or not in the correct location.
Example:
# Importing a non-existent function from the built-in math module from math import non_existent_function
This will raise the following exception:
ImportError: cannot import name 'non_existent_function' from 'math' (unknown location)
To fix an ImportError
, you can:
pip install module_name
for third-party modules).ModuleNotFoundError
is a subclass of ImportError
that is raised when the interpreter cannot find the specified module. This can happen if the module is misspelled, not installed, or not in the correct location.
Example:
# Trying to import a non-existent module import non_existent_module
This will raise the following exception:
ModuleNotFoundError: No module named 'non_existent_module'
To fix a ModuleNotFoundError
, you can:
pip install module_name
for third-party modules).In summary, both ImportError
and ModuleNotFoundError
are related to issues with importing modules or their components. The main difference is that ImportError
is more general and can be raised when importing a specific object fails, while ModuleNotFoundError
is specifically raised when the module itself cannot be found. To fix these errors, check the spelling, installation, and location of the modules and objects you're trying to import.
Handling missing module errors in Python:
try: import missing_module except ModuleNotFoundError: print("Module not found. Handle the error gracefully.")