Importing Standard and External Modules in Python
Python is a versatile programming language with a rich ecosystem of modules that can be used to extend its functionality. Modules in Python are categorized into standard modules (built-in) and external modules (third-party libraries). This article demonstrates how to import these modules with examples.
1. Importing Standard Modules
Standard modules are part of Python's standard library. These modules are included in Python's default installation, and you don't need to install them separately.
Here are a few examples of using standard modules:
Example 1: Importing the math
Module
import math # Using the sqrt function result = math.sqrt(16) print("Square root of 16 is:", result)
Example 2: Importing the datetime
Module
import datetime # Getting the current date and time current_time = datetime.datetime.now() print("Current date and time:", current_time)
Example 3: Importing Specific Functions
from math import pi, sin # Using the imported functions angle = pi / 2 print("Sine of 90 degrees:", sin(angle))
2. Importing External Modules
External modules are not included with Python by default. They need to be installed using package managers like pip
.
Here are some examples of using external modules:
Example 1: Importing the requests
Module
First, install the module using the command: pip install requests
.
import requests # Sending a GET request response = requests.get("https://api.github.com") print("Response status code:", response.status_code)
Example 2: Importing the numpy
Module
First, install the module using the command: pip install numpy
.
import numpy as np # Creating an array array = np.array([1, 2, 3, 4]) print("Array:", array)
Example 3: Importing a Module with an Alias
import matplotlib.pyplot as plt # Creating a simple plot plt.plot([1, 2, 3], [4, 5, 6]) plt.title("Simple Plot") plt.show()
Conclusion
Understanding how to import standard and external modules is essential for leveraging Python's extensive functionality. While standard modules are readily available, external modules offer additional capabilities that require installation. By mastering both types of modules, you can enhance your Python projects significantly.