SAMANTUS Python for Data Analytics — Complete Training Manual MODULE 12
← Back to Course Index

Python Modules


On This Page

Module 12: Python Modules


12.1  What is a Module?

A module is simply a file containing pre-written Python code (functions, classes, variables) that you can import and reuse in your own programs — saving you from reinventing the wheel for common tasks.

► Basic Import Syntax
import math
from datetime import datetime
import random as rnd     # import with an alias

12.2  The math Module

Covered in detail in Module 4 — provides advanced mathematical functions.

► Quick Recap
import math
print(math.sqrt(81))     # 9.0
print(math.pi)           # 3.14159...

12.3  The random Module

The random module generates random numbers and selections — useful for simulations, sampling data, and generating test/dummy data.

► Common random Functions
import random

print(random.randint(1, 100))         # random whole number 1-100
print(random.choice(["A","B","C"]))   # random pick from a list

students = ["Priya", "Rahul", "Anita", "Vikram"]
random.shuffle(students)              # shuffles the list in place
print(students)
✓ Real-World Use Case
random.sample() is commonly used to select a random subset of customer data for A/B testing or quality-check sampling in analytics projects.

12.4  The statistics Module

The statistics module provides ready-made functions for common statistical calculations — a preview of what NumPy and Pandas will do at scale later in this course.

► Common statistics Functions
import statistics

marks = [78, 85, 92, 66, 88, 74]
print("Mean:", statistics.mean(marks))
print("Median:", statistics.median(marks))
print("Mode:", statistics.mode(marks))
print("Std Dev:", round(statistics.stdev(marks), 2))
Output
Mean: 80.5
Median: 81.5
Mode: 78
Std Dev: 9.34

12.5  The datetime Module

The datetime module handles dates and times — essential for timestamps, deadlines, reports, and scheduling logic.

► Working with Dates
from datetime import datetime, timedelta

now = datetime.now()
print("Current date & time:", now)
print("Formatted:", now.strftime("%d-%m-%Y"))

deadline = now + timedelta(days=7)
print("Assignment due:", deadline.strftime("%d-%m-%Y"))
✓ Instructor Tip
strftime() format codes are frequently confused by beginners — keep a printed cheat sheet handy: %d (day), %m (month), %Y (year), %H (hour), %M (minute).

12.6  The os Module

The os module lets Python interact with the operating system — checking folders, listing files, and managing paths.

► Common os Functions
import os

print(os.getcwd())              # current working directory
print(os.listdir("."))          # list files in current folder
os.makedirs("reports", exist_ok=True)   # create a folder safely

12.7  The sys Module

The sys module provides access to system-specific parameters, such as command-line arguments and the Python version being used.

► Common sys Functions
import sys

print(sys.version)      # Python version info
# sys.exit()            # stops program execution immediately
ModuleBest Used For
mathPrecise mathematical calculations
randomRandom values, shuffling, sampling
statisticsQuick mean/median/mode/std-dev calculations
datetimeWorking with dates, times, deadlines
osFile system & folder operations
sysSystem-level info & program control

12.8  Practical Exercises

Basic (5 Questions)

1. Generate a random number between 1 and 50 using the random module.

2. Print today's date using the datetime module.

3. Calculate the mean and median of a list of 6 numbers using statistics.

4. List all files in your current folder using the os module.

5. Print your installed Python version using the sys module.

Intermediate (5 Questions)

1. Shuffle a list of 10 student names using random.shuffle().

2. Calculate an assignment deadline 5 days from today using timedelta.

3. Find the standard deviation of a list of exam scores using statistics.stdev().

4. Create a new folder using os.makedirs() only if it doesn't already exist.

5. Format the current date as 'DD-Month-YYYY' (e.g. 15-March-2026) using strftime().

Advanced (5 Questions)

1. Build a random 'Quiz Question Picker' that selects 5 unique questions from a list of 20 using random.sample().

2. Build a program that calculates how many days remain until a given course start date.

3. Write a program that generates a summary report (mean, median, mode, std dev) for a marks dataset using statistics.

4. Build a simple file-organizer script using os that lists all files in a folder and counts how many are .csv vs .txt.

5. Combine datetime and random to build a 'Random Class Scheduler' that assigns random time slots to 5 courses this week.

12.9  Module Quiz (MCQs)

Q1. Which module generates random numbers?

Q2. Which function returns the current date and time?

Q3. Which module calculates mean, median, and mode easily?

Q4. Which module helps list files in a folder?

Q5. What does sys.exit() do?

ℹ Answer Key
1-b, 2-b, 3-b, 4-a, 5-c

12.10  Module Assignment

Assignment: Random Quiz & Report Generator

Expected Output: A working script combining random, statistics, and datetime modules to produce a mini quiz-and-results report.

12.11  Interview Questions — Module 12


12.12  Student Notes Page

Use this space to write down key points, doubts, and your own examples from today's session.