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.
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:
math
Moduleimport math # Using the sqrt function result = math.sqrt(16) print("Square root of 16 is:", result)
datetime
Moduleimport datetime # Getting the current date and time current_time = datetime.datetime.now() print("Current date and time:", current_time)
from math import pi, sin # Using the imported functions angle = pi / 2 print("Sine of 90 degrees:", sin(angle))
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:
requests
ModuleFirst, 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)
numpy
ModuleFirst, 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)
import matplotlib.pyplot as plt # Creating a simple plot plt.plot([1, 2, 3], [4, 5, 6]) plt.title("Simple Plot") plt.show()
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.