Python ModulesIntroduction

Introduction to Python Modules

Python modules are reusable pieces of code that simplify programming by providing pre-defined functionalities. A module can contain functions, classes, and variables that you can import into your program to extend its capabilities.


What Are Modules?

A module in Python is simply a file with the .py extension that contains Python code. You can:

  • Use built-in modules provided by Python.
  • Create your custom modules for specific tasks.
  • Install third-party modules using pip.

Why Use Modules?

Modules offer the following benefits:

  1. Code Reusability

    • Write a function once and use it across multiple projects by importing the module.
  2. Saves Time

    • Instead of writing code from scratch, use pre-built modules to achieve your goal faster.
  3. Better Code Organization

    • Split large programs into smaller, logical pieces using modules.
  4. Enhanced Functionality

    • Access advanced features like web scraping, data analysis, or GUI development using third-party modules.

Importing Modules

You can import a module in various ways:

  1. Basic Import

    import math
    print(math.sqrt(16))  # Output: 4.0
  2. Import Specific Functions

    from math import sqrt
    print(sqrt(25))  # Output: 5.0
  3. Alias Modules

    import pandas as pd
    df = pd.DataFrame({"Name": ["Rhea", "Nitya"], "Age": [25, 30]})
    print(df)
  4. Import All Functions (Not Recommended)

    from math import *
    print(sin(90))

Types of Modules

  1. Built-In Modules

    • Already included in Python and require no installation.
    • Examples: os, sys, math, random.
  2. Third-Party Modules

    • Developed by the Python community and installed via pip.
    • Examples: numpy, requests, matplotlib.
  3. Custom Modules

    • Created by users to organize their reusable code.

CategoryModulePurpose
MathematicsmathProvides mathematical functions and constants.
randomGenerates random numbers for various use cases.
Data AnalysispandasData manipulation and analysis.
numpyNumerical computations.
Web DevelopmentflaskLightweight web framework.
djangoHigh-level framework for scalable web apps.
Web ScrapingrequestsMakes HTTP requests to access web data.
beautifulsoup4Parses HTML for web scraping.
Machine Learningscikit-learnImplements ML algorithms.
tensorflowFor deep learning models.
AutomationpyautoguiAutomates keyboard and mouse actions.
seleniumAutomates browser tasks.
Image ProcessingpillowProcesses and manipulates images.
opencvAdvanced image and video processing.
Game DevelopmentpygameUsed for creating 2D games.
CryptographycryptographyProvides encryption and hashing tools.

How to Install Third-Party Modules?

You can install third-party modules using pip, the Python package manager.
For example, to install the requests module, run the following command in your terminal:

pip install requests

Example:

import requests
 
response = requests.get("https://www.pythonforall.com")
print(response.status_code)

Creating Your Own Module

You can create a module by saving a Python file with functions, classes, or variables.

Example: Creating a Custom Module

File: greetings.py

def say_hello(name):
    print(f"Hello, {name}! Welcome to PythonForAll.")

File: main.py

import greetings
 
greetings.say_hello("Rhea")
# Output: Hello, Rhea! Welcome to PythonForAll.

Best Practices for Using Modules

  1. Use Built-In Modules First

    • Always check if Python provides a built-in module before installing third-party ones.
  2. Follow Naming Conventions

    • Use descriptive names for custom modules.
  3. Avoid Name Conflicts

    • Ensure your custom module names don’t clash with built-in or popular third-party modules.
  4. Keep Code Organized

    • Store your modules in separate files or folders for better project structure.

Try It Yourself

Problem 1: Import and Use the math Module

Write a program to calculate the area of a circle given its radius using the math module.

Show Code
import math
 
radius = float(input("Enter the radius of the circle: "))
area = math.pi * math.pow(radius, 2)
print("Area of the circle:", area)

Problem 2: Create and Use a Custom Module

Write a custom module calculator.py that contains functions for addition and multiplication. Import and use it in another script.

Show Code

File: calculator.py

def add(a, b):
    return a + b
 
def multiply(a, b):
    return a * b

File: main.py

import calculator
 
print("Sum:", calculator.add(5, 3))        # Output: Sum: 8
print("Product:", calculator.multiply(5, 3))  # Output: Product: 15