Select Page

Modules and libraries in Python provide additional functionality that extends the capabilities of the core language. They contain pre-written code and tools that can be imported and used in our programs. Python has a vast ecosystem of libraries that cover various domains, such as data analysis, web development, machine learning, and more.

Let’s explore how to use modules and libraries in Python:

``````# Importing a module
import math

# Using functions from the math module
print("Square root of 16:", math.sqrt(16))
print("Value of pi:", math.pi)

# Importing specific functions from a module
from random import randint

# Using the imported function
random_number = randint(1, 10)
print("Random number:", random_number)

# Importing an entire library with an alias
import numpy as np

# Using functions from the numpy library
array = np.array([1, 2, 3, 4, 5])
print("Array:", array)
print("Sum of array elements:", np.sum(array))``````

# Explanation:

• We import the `math` module to access mathematical functions and constants.
• We use the `math.sqrt()` function to calculate the square root of a number and access the value of pi using `math.pi`.
• We import the `randint` function from the `random` module to generate random numbers.
• We import the `numpy` library with the alias `np` for numerical computing and work with arrays using functions like `np.array()` and `np.sum()`.

Now it’s time for a practical task:

Write a Python program that uses the `datetime` module to display the current date and time. Import the necessary function(s) from the `datetime` module, retrieve the current date and time, and print it in a readable format.