Modules in Python

Getting your Trinity Audio player ready...

When you start writing Python programs, you’ll often need extra tools to perform tasks like handling dates, working with text patterns, saving data in CSV or JSON, and much more.

Instead of writing all the code from scratch, Python gives you Modules — pre-written code that you can import and use directly in your programs.

Modules in Python

What are Modules in Python?

A module is simply a file that contains Python code (functions, classes, variables).
Modules help you:

  • Reuse code without rewriting it
  • Organize large projects
  • Access powerful built-in features

👉 Example:

import math

print(math.sqrt(16))   # Output: 4.0
print(math.pi)         # Output: 3.141592653589793

Here, we used the math module to calculate a square root and access the value of pi.


Types of Modules

  1. Built-in Modules → Already included with Python (e.g., math, datetime, os, re, csv, json).
  2. User-defined Modules → Python files you create to reuse your own code.
  3. External Modules → Installed from the internet using pip (e.g., numpy, pandas, requests).

Importing Modules

There are different ways to import modules:

import math              # Import full module
from math import sqrt    # Import specific function
import math as m         # Import with alias

Important Built-in Modules in Python

Now let’s explore some useful built-in modules with real-life examples.


1. datetime – Working with Date and Time

from datetime import datetime, date

# Current date and time
now = datetime.now()
print("Now:", now)

# Current date
today = date.today()
print("Today:", today)

# Formatting date
print("Formatted:", now.strftime("%d-%m-%Y %H:%M:%S"))

# Converting string to date
dob = datetime.strptime("15-08-1995", "%d-%m-%Y")
print("DOB:", dob.date())

✅ Use Case: Track user registration time, calculate age, log transactions.

Read More: Date and Time in Python


2. re – Regular Expressions (Pattern Matching)

import re

text = "My phone number is 9876543210"

# Find digits
match = re.search(r"\d{10}", text)
if match:
    print("Phone found:", match.group())

# Replace text
updated = re.sub(r"\d{10}", "**********", text)
print(updated)

✅ Use Case: Validate emails, phone numbers, or passwords in forms.


3. csv – Handling CSV Files

import csv

# Writing to CSV
with open("students.csv", "w", newline="") as file:
    writer = csv.writer(file)
    writer.writerow(["Name", "Age"])
    writer.writerow(["Ramesh", 21])
    writer.writerow(["Sita", 22])

# Reading from CSV
with open("students.csv", "r") as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)

✅ Use Case: Store and manage structured data like student records, sales reports.


4. json – Working with JSON Data

import json

# Dictionary to JSON
student = {"name": "Ramesh", "age": 21, "course": "Python"}
json_data = json.dumps(student)
print("JSON:", json_data)

# JSON to Dictionary
data = '{"name": "Sita", "age": 22, "course": "Data Science"}'
student_dict = json.loads(data)
print("Dictionary:", student_dict)

✅ Use Case: APIs, web applications, storing structured data.


Creating Your Own Module

You can also create your own module.

👉 Create a file my_module.py

def greet(name):
    return f"Hello, {name}! Welcome to Python."

👉 Use it in another file:

import my_module

print(my_module.greet("Ramesh"))

Final Thoughts

Modules are the backbone of Python programming.

  • They save you from rewriting code
  • Make your programs more powerful
  • Keep your project well-organized

What’s Next?

In the next post, we’ll learn about the Date and Time in Python

Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *

Translate »
Scroll to Top