Learn Module in Python Programming

Learn Module in Python Programming

Learn Module in Python Programming

Hello everyone, today we will talk about Python programming modules. We will learn about Python modules with examples and explanations in this module post, so you need to have read and practiced if you followed our prior Python topic.

Let’s start…

Introduction to Python Modules:

What are modules in Python?

In Python programming, modules are files that hold Python code. They have the ability to declare variables, classes, and methods that you can use in other Python scripts. Modules facilitate the organization of your code into reusable parts and ease the management of sizable 
codebases. Using the import statement, you can import modules into your Python scripts or interactive sessions to use 
them. You can build your own modules to encapsulate functionality and encourage code reusability, in addition to the many modules in the Python standard library that are available for different tasks.

How to Use Modules?

Import the module: First, you need to import the module you want to use. You can do this using the import keyword followed by the name of the module. Below, we import the math module to do mathematical operations.

For example:

import math

Access functions and variables:
Once the module is imported, you can access its functions and variables using dot notation. For example, if you want to use the sqrt() function from the math module to find the square root of a number:

import math
result = math.sqrt(144)
print(result)  # Output will be 12.0

Module names (optional):
You can also give a module a different name, when you import it, using the as keyword. This can make the module name shorter or easier to remember.

For example:

    import math as aa

    result = aa.sqrt(25)
    print(result)  # Output will be 5.0

Import specific functions (optional):
Instead of importing the entire module, you can import specific functions or variables from the module using the from keyword. For example, if you only want to use the sqrt() function from the math module:

    from math import sqrt
    result = sqrt(81)
    print(result)  # Output will be 9.0

Types of modules in Python:

In Python, modules can generally be categorized into three main types based on their source and usage:

i. Built-in Modules: These are modules that come pre-installed with Python. Examples include modules like math, random, os, sys, and datetime. These modules provide a wide range of functionalities for various tasks without requiring any additional installation.

ii. Standard Library Modules: These are modules that are part of Python’s standard library but are not built-in. They are included with Python installations but may need to be imported explicitly before use. Examples include modules like csv, json, re, collections, and time.

iii. Third-Party Modules: These are modules developed by third-party developers and are not included with Python’s standard library. They need to be installed separately, usually using package managers like pip. Third-party modules extend Python’s capabilities by providing specialized functionalities for specific tasks. Examples include modules like numpy, pandas, requests, matplotlib, and tensorflow. These modules cater to diverse needs ranging from data analysis and machine learning to web development and graphical plotting.

Built-in Modules

Built-in modules in Python are modules that come pre-installed with the Python programming language. These modules provide a wide range of functionalities for various tasks without requiring any additional installation.

Below are some examples of built-in modules in Python along with their functionalities:

math: This module provides mathematical functions and constants. For example, you can use it to perform operations like square root, trigonometric functions, and logarithms.

import math

print(math.sqrt(25))  # Output: 5.0
print(math.sin(math.pi / 2))  # Output: 1.0

random: This module is used for generating random numbers and selecting random items from lists.


    import random

    # Output: Random integer between 1 and 100
    print(random.randint(1,100))

    # Output: Randomly selected item from the list
    print(random.choice(["Apple","Graps","Banana","Orange","Pineapple"]))

datetime: This module helps in working with dates and times.


    import datetime

    current_time = datetime.datetime.now()
    print(current_time)   # Output: Current date and time

os: This module provides functions for interacting with the operating system, such as file operations, directory operations, and process management.

import os

print(os.getcwd())    # Output: Current working directory

sys: This module provides access to some variables used or maintained by the Python interpreter and functions that interact strongly with the interpreter.

    import sys

    print(sys.version)

Standard Library Modules:

Below are some examples of Standard Library Modules in Python along with their functionalities:

csv:
The below code reads data from a CSV (Comma Separated Values) file named data.csv and prints each row of data. The csv module provides functions for reading and writing CSV files, making it easy to work with tabular data.

    import csv

    with open('data.csv', 'r') as file:
        reader = csv.reader(file)
        for row in reader:
            print(row)

json:
The below code demonstrates how to convert a Python dictionary into a JSON (JavaScript Object Notation) string using the json module’s dumps() function. JSON is a popular data interchange format, and the json module allows you to work with JSON data in Python effortlessly.

import json

data = {'name': 'John', 'age': 30}
json_string = json.dumps(data)  # Convert Python dictionary to JSON string
print(json_string)

re:
This code uses the re module to perform pattern matching on a string. It finds all words in the text that have exactly 5 characters. Regular expressions, supported by the re module, are powerful tools for searching and manipulating strings based on patterns.

import re

text = "The quick brown fox jumps over the lazy dog"
pattern = r'\b\w{5}\b'  # Match words with 5 characters
result = re.findall(pattern, text)
print(result)

Third-Party Modules:

Requests:
The requests module allows Python programs to send HTTP requests easily.

With the requests module, you can make requests to web servers to fetch data from URLs, interact with RESTful APIs, or even perform web scraping. It simplifies the process of making HTTP requests and handling responses in Python.
Example:

import requests

response = requests.get('https://api.github.com/')
print(response.status_code)  # Output: 200

Pillow (Python Imaging Library, forked as Pillow):

The Pillow module allows Python programs to work with images.
With Pillow, you can open, manipulate, and save images in various formats like JPEG, PNG, GIF, and BMP. It provides functionalities for tasks such as resizing images, applying filters, and converting between different image formats.

Example:

from PIL import Image

image = Image.open('example.jpg')
image.show()

matplotlib:

The matplotlib module is used for creating static, animated, and interactive visualizations in Python.
With matplotlib, you can create various types of plots and charts, such as line plots, scatter plots, bar plots, histograms, and pie charts. It provides a flexible and powerful toolkit for data visualization.

Example:

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
plt.plot(x, y)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Example Plot')
plt.show()

numpy:

The numpy module provides support for numerical computing in Python.

numpy offers a powerful array object called numpy.ndarray and a collection of functions for performing mathematical operations on arrays efficiently. It is widely used for tasks such as array manipulation, linear algebra, Fourier transforms, and random number generation.

Example:

import numpy as np

arr = np.array([1, 2, 3, 4, 5])
print(arr.mean())  # Output: 3.0

pandas:

The pandas module provides high-performance, easy-to-use data structures and data analysis tools for Python.

With pandas, you can work with structured data like tables, perform data manipulation operations, handle missing data, and perform data analysis tasks such as filtering, grouping, and aggregation. It is widely used for data cleaning, exploration, and preparation in data science projects.

Example:

import pandas as pd

data = {'Name': ['John', 'Alice', 'Bob'], 'Age': [25, 30, 35]}
df = pd.DataFrame(data)
print(df)

Leave a Reply