How to Import Module in Python: Simple Guide
In Python, you import a module using the
import keyword followed by the module name. This allows you to use functions, classes, or variables defined in that module in your code.Syntax
The basic syntax to import a module is:
import module_name: Imports the whole module.from module_name import item: Imports a specific function, class, or variable from the module.import module_name as alias: Imports the module with a shorter name (alias) for easier use.
python
import math from math import sqrt import math as m
Example
This example shows how to import the math module and use its sqrt function to calculate the square root of a number.
python
import math number = 16 result = math.sqrt(number) print(f"The square root of {number} is {result}")
Output
The square root of 16 is 4.0
Common Pitfalls
Common mistakes when importing modules include:
- Forgetting to install third-party modules before importing them.
- Using incorrect module names or typos.
- Confusing
import modulewithfrom module import item. - Overwriting module names with variables in your code.
python
import math math = 5 # Wrong: overwrites the module print(math.sqrt(16)) # This will cause an error # Correct way: import math print(math.sqrt(16))
Output
Traceback (most recent call last):
File "<stdin>", line 3, in <module>
AttributeError: 'int' object has no attribute 'sqrt'
# Correct output:
4.0
Quick Reference
Here is a quick summary of import styles:
| Import Style | Description | Example |
|---|---|---|
| Import whole module | Imports entire module to use with module prefix | import math |
| Import specific item | Imports only one function/class/variable | from math import sqrt |
| Import with alias | Imports module with a short name | import math as m |
Key Takeaways
Use
import module_name to bring a whole module into your code.Use
from module_name import item to import specific parts of a module.Avoid overwriting module names with variables to prevent errors.
Use aliases with
import module_name as alias for shorter code.Always check module names and install third-party modules before importing.