PYTHON MODULES & IMPORTS

Organize code into reusable files, import built-in libraries, and manage custom packages using the import statement in Python.

📦 What is a Module in Python?

A module is simply a Python file (ending in .py) containing executable code, function definitions, classes, and variables. Modules allow you to break down large programs into manageable, reusable files. You can bring external or custom modules into your current script using the import keyword.

1. Importing Built-in Modules (math module)
Import Python's built-in standard library modules like math to perform mathematical operations.
Python
import math

# Using functions from the math module
print("Square root of 64:", math.sqrt(64))
print("Value of Pi:", math.pi)
print("Factorial of 5:", math.factorial(5))
Output: Square root of 64: 8.0 Value of Pi: 3.141592653589793 Factorial of 5: 120
Real-Time Example 1: Working with Dates & Times (datetime module)
Generate timestamps and format dates using Python's datetime module.
Python
import datetime

# Get current date and time
now = datetime.datetime.now()

print("Current Date & Time:", now)
print("Formatted Date:", now.strftime("%d-%m-%Y"))
print("Current Year:", now.year)
print("Day of the week:", now.strftime("%A"))
Output: Current Date & Time: 2026-10-27 22:08:00.123456 Formatted Date: 27-10-2026 Current Year: 2026 Day of the week: Tuesday
Real-Time Example 2: Importing Specific Functions (from ... import)
Import specific functions or classes directly from a module without referencing the module prefix.
Python
# Import specific functions directly
from math import sqrt, pow

print("Square root of 144:", sqrt(144))
print("2 raised to power 3 (2^3):", pow(2, 3))
Output: Square root of 144: 12.0 2 raised to power 3 (2^3): 8.0
Real-Time Example 3: Aliasing Modules (import as)
Rename modules using an alias (as keyword) to shorten long module names or avoid naming conflicts.
Python
import datetime as dt

# Using the alias 'dt'
today = dt.date.today()
print("Today's Date:", today)
Output: Today's Date: 2026-10-27
Real-Time Example 4: Generating Random Data (random module)
Generate random numbers, pick random choices, or shuffle lists using the random module.
Python
import random

# Random integer between 1 and 10
otp_code = random.randint(1000, 9999)
print("Generated OTP Code:", otp_code)

# Random selection from a list
items = ["Mouse", "Keyboard", "Monitor", "Webcam"]
selected_item = random.choice(items)
print("Lucky Door Prize Winner Item:", selected_item)
Output: Generated OTP Code: 4829 Lucky Door Prize Winner Item: Keyboard
Real-Time Example 5: Operating System Utilities (os module)
Interact with the underlying operating system to inspect directories, environment variables, and file paths.
Python
import os

# Get current working directory
current_dir = os.getcwd()
print("Current Working Directory:", current_dir)

# Check environment variables
print("OS Platform Name:", os.name)
Output: Current Working Directory: /home/user/python_projects OS Platform Name: posix
Real-Time Example 6: Creating and Importing Custom Modules
Create your own custom module (e.g., tax_calculator.py) and import it into another script.
Python
# Inside file: tax_calculator.py
# def calculate_gst(amount):
#     return amount * 0.18

# Inside main script:
# import tax_calculator
# print("Calculated GST:", tax_calculator.calculate_gst(2500))

print("Custom module creation and import architecture explained successfully.")
Output: Custom module creation and import architecture explained successfully.
Real-Time Example 7: Inspecting Module Contents (dir() function)
Use Python's built-in dir() function to list all attributes and functions available inside a module.
Python
import math

# List all functions and variables in math module
math_attributes = dir(math)
print("First 5 attributes of math module:", math_attributes[:5])
Output: First 5 attributes of math module: ['__doc__', '__loader__', '__name__', '__package__', '__spec__']
Real-Time Example 8: Handling Missing Modules (ModuleNotFoundError)
Catch module import errors gracefully when third-party packages are not installed.
Python
try:
    import non_existent_package
except ModuleNotFoundError as e:
    print("Exception Caught: Required module is not installed.", e)
Output: Exception Caught: Required module is not installed. No module named 'non_existent_package'
Real-Time Example 9: JSON Serialization Module (json module)
Import Python's built-in json module to encode and decode JSON data strings.
Python
import json

user_data = {"name": "Nikita Infotech", "active": True, "score": 98.5}

# Convert dictionary to JSON string
json_string = json.dumps(user_data, indent=2)
print("Encoded JSON String:\n" + json_string)

# Convert JSON string back to dictionary
parsed_dict = json.loads(json_string)
print("Parsed Dictionary Name:", parsed_dict["name"])
Output: Encoded JSON String: { "name": "Nikita Infotech", "active": true, "score": 98.5 } Parsed Dictionary Name: Nikita Infotech