-
1. Introduction to Python
-
2. Python Basics
-
3. Working with Data Structures
-
4. Functions and Modules
-
5. Object-Oriented Programming (OOP)
-
6. File Handling
-
7. Error and Exception Handling
-
8. Python for Data Analysis
-
9. Advanced Topics in Python
-
10. Working with APIs
-
11. Python for Automation
-
12. Capstone Projects
- 13. Final Assessment and Quizzes
4.3 Importing and Using Modules
In Python, modules are files containing Python code that can define functions, classes, and variables, as well as include runnable code. Modules help you organize and structure your code, enabling you to reuse code across multiple programs. Python has a large standard library of built-in modules, and you can also import third-party libraries or your custom modules.
1. Importing a Module
To use the functionality defined in a module, you first need to import it into your script using the import statement. Here’s how you can import a module:
1.1 Importing the Whole Module
You can import an entire module and use its functions by referencing the module name.
Example:
import math # Using the math module to calculate the square root print(math.sqrt(16)) # Output: 4.0
1.2 Importing Specific Functions or Variables
Instead of importing the whole module, you can import only the specific functions or variables you need.
Example:
from math import sqrt # Using the sqrt function directly print(sqrt(16)) # Output: 4.0
1.3 Importing with Aliases
You can also assign an alias to the module or function while importing it, which is helpful to simplify long names or avoid name conflicts.
Example:
import math as m # Using the math module with an alias print(m.sqrt(16)) # Output: 4.0
2. Using Built-in Modules
Python has many built-in modules in its standard library that you can use without installing any additional packages. Some common built-in modules are:
- math: Provides mathematical functions such as sqrt(), sin(), cos(), and more.
- random: For generating random numbers and making random selections.
- datetime: For working with dates and times.
- os: Provides functions to interact with the operating system, such as file handling and environment variables.
Example using the random module:
import random # Generate a random integer between 1 and 100 print(random.randint(1, 100))
3. Using External Modules (Third-Party Libraries)
In addition to Python's built-in modules, you can also install and use third-party libraries. These are not included by default but can be installed using a package manager like pip.
Example of installing a third-party library:
pip install requests
Once the module is installed, you can import and use it as follows:
import requests # Fetching data from a URL using requests response = requests.get('https://jsonplaceholder.typicode.com/posts') print(response.json()) # Display the fetched data
4. Creating Your Own Modules
You can create your own modules by saving Python code in .py files and then importing it into other Python scripts.
Example:
- Create a module (save as mymodule.py):
# mymodule.py def greet(name): return f"Hello, {name}!"
- Import and use the module:
# main.py import mymodule print(mymodule.greet("Alice")) # Output: Hello, Alice!
5. Using __name__ in Modules
In Python, you can check if a module is being run directly or being imported into another script using the special __name__ variable. If a module is run directly, __name__ will be set to "__main__". If the module is imported, __name__ will be set to the module's name.
Example:
# mymodule.py def greet(name): return f"Hello, {name}!" if __name__ == "__main__": print(greet("Main Program"))
If you run mymodule.py directly, it will print Hello, Main Program. But if you import it into another script, the if __name__ == "__main__": block will not execute.
6. Reloading Modules
If you make changes to a module and want to reload it without restarting the Python interpreter, you can use the reload() function from the importlib module:
from importlib import reload import mymodule reload(mymodule)
Summary
- import: Imports a whole module.
- from ... import: Imports specific functions or variables from a module.
- as: Assigns an alias to a module or function.
- Built-in modules like math, random, datetime are available for immediate use.
- External modules (third-party libraries) can be installed using pip.
- You can create custom modules by saving Python code in .py files and importing them.
Commenting is not enabled on this course.