Modules & Libraries in Python

Modules and Imports

What is a Module?

So far you've written everything from scratch. But Python comes with hundreds of pre-built modules — ready-made code that solves common problems.

Instead of writing code to get current date, generate random numbers, do math operations, work with files — Python already has it all built in. You just import it and use it.

Real life analogy: Modules are like apps on your phone. You don't build a calculator app from scratch — you just open the pre-installed one and use it.


Basic Import Syntax

import module_name

module_name.function_name()

Or import specific things from a module:

from module_name import function_name

function_name()    # no need to write module_name. prefix

Built-in Modules

These come with Python — no installation needed.


1. math — Mathematical Operations


    import math

    print(math.pi)              # 3.141592653589793
    print(math.e)               # 2.718281828459045

    print(math.sqrt(16))        # 4.0  — square root
    print(math.pow(2, 10))      # 1024.0 — power
    print(math.floor(4.9))      # 4  — round down
    print(math.ceil(4.1))       # 5  — round up
    print(math.fabs(-7))         # 7  — absolute value
    print(math.factorial(5))    # 120 — 5! = 5*4*3*2*1

    print(math.log(100, 10))    # 2.0 — log base 10 of 100
    print(math.sin(math.pi/2))  # 1.0 — sine of 90 degrees


2. random — Random Numbers


    import random

    # Random float between 0 and 1
    print(random.random())              # 0.7364... something

    # Random integer between two numbers (inclusive)
    print(random.randint(1, 10))        # random number 1 to 10

    # Random float between two numbers
    print(random.uniform(1.5, 5.5))     # random float between 1.5 and 5.5

    # Pick random item from a list
    fruits = ["apple", "banana", "mango", "orange"]
    print(random.choice(fruits))        # random fruit

    # Pick multiple random items (no repetition)
    print(random.sample(fruits, 2))     # 2 random fruits

    # Shuffle a list in place
    numbers = [1, 2, 3, 4, 5]
    random.shuffle(numbers)
    print(numbers)                      # shuffled list

Real use case — OTP generator:


    import random

    def generate_otp():
        return random.randint(100000, 999999)

    otp = generate_otp()
    print(f"Your OTP is: {otp}")


3. datetime — Dates and Times


    from datetime import datetime, date, timedelta

    # Current date and time
    now = datetime.now()
    print(now)                              # 2025-03-03 10:30:45.123456

    # Formatted output
    print(now.strftime("%d-%m-%Y"))         # 03-03-2025
    print(now.strftime("%d %B %Y"))         # 03 March 2025
    print(now.strftime("%I:%M %p"))         # 10:30 AM
    print(now.strftime("%Y-%m-%d %H:%M:%S")) # 2025-03-03 10:30:45

    # Access individual parts
    print(now.year)                         # 2025
    print(now.month)                        # 3
    print(now.day)                          # 3
    print(now.hour)                         # 10
    print(now.minute)                       # 30

    # Today's date only
    today = date.today()
    print(today)                            # 2025-03-03

    # Date arithmetic
    tomorrow = today + timedelta(days=1)
    last_week = today - timedelta(days=7)
    print(f"Tomorrow: {tomorrow}")
    print(f"Last week: {last_week}")

strftime format codes:

Code

Meaning

Example

%d

Day

03

%m

Month number

03

%B

Month name

March

%Y

Full year

2025

%H

Hour 24hr

14

%I

Hour 12hr

02

%M

Minutes

30

%S

Seconds

45

%p

AM/PM

PM



4. os — Operating System Operations


    import os

    # Current directory
    print(os.getcwd())                      # /home/gagan/python-learning

    # List files in directory
    print(os.listdir("."))                  # ['.', list of files]

    # Check if file/folder exists
    print(os.path.exists("notes.txt"))      # True or False

    # Create a folder
    os.makedirs("my_folder", exist_ok=True) # exist_ok=True won't error if already exists

    # Join paths properly (works on all OS)
    path = os.path.join("my_folder", "data", "file.txt")
    print(path)                             # my_folder/data/file.txt

    # Get filename and extension
    filename = "document.txt"
    print(os.path.splitext(filename))       # ('document', '.txt')

    # Delete a file
    # os.remove("file.txt")

    # Rename a file
    # os.rename("old.txt", "new.txt")


5. string — String Constants


    import string

    print(string.ascii_lowercase)   # abcdefghijklmnopqrstuvwxyz
    print(string.ascii_uppercase)   # ABCDEFGHIJKLMNOPQRSTUVWXYZ
    print(string.digits)            # 0123456789
    print(string.punctuation)       # !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~

Real use case — Password generator:


    import random
    import string

    def generate_password(length=12):
        characters = string.ascii_letters + string.digits + string.punctuation
        password = ""
        for i in range(length):
            password += random.choice(characters)
        return password

    print(generate_password())        # random 12 character password
    print(generate_password(16))      # random 16 character password


6. json — Working with JSON Data

JSON is the most common data format for APIs and web applications. It looks exactly like Python dictionaries:


    import json

    # Python dictionary to JSON string
    person = {
        "name": "Gagan",
        "age": 22,
        "city": "Delhi",
        "skills": ["Python", "JavaScript"]
    }

    json_string = json.dumps(person)
    print(json_string)
    print(type(json_string))    # <class 'str'>

    # Pretty printed JSON
    print(json.dumps(person, indent=4))

Output:

{
    "name": "Gagan",
    "age": 22,
    "city": "Delhi",
    "skills": [
        "Python",
        "JavaScript"
    ]
}

    import json

    # JSON string back to Python dictionary
    json_data = '{"name": "Gagan", "age": 22, "city": "Delhi"}'
    person = json.loads(json_data)
    print(person["name"])       # Gagan
    print(type(person))         # <class 'dict'>

Save and load JSON from file — very common pattern:


    import json

    # Save to file
    data = {"users": ["Rahul", "Priya", "Gagan"], "count": 3}

    with open("data.json", "w") as file:
        json.dump(data, file, indent=4)

    print("Saved!")

    # Load from file
    with open("data.json", "r") as file:
        loaded_data = json.load(file)

    print(loaded_data)
    print(loaded_data["users"])     # ['Rahul', 'Priya', 'Gagan']

JSON is much better than plain text files for saving structured data like dictionaries and lists.


Creating Your Own Module

A module is just a Python file. Any .py file you create can be imported by other files.

Create a file called helpers.py:


    # helpers.py

    def greet(name):
        return f"Hello, {name}!"

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

    def is_even(n):
        return n % 2 == 0

    PI = 3.14159

Now in your main file main.py (in the same folder):


    # main.py

    import helpers

    print(helpers.greet("Gagan"))       # Hello, Gagan!
    print(helpers.add(5, 3))            # 8
    print(helpers.is_even(4))           # True
    print(helpers.PI)                   # 3.14159

Or import specific things:


    from helpers import greet, add

    print(greet("Gagan"))               # Hello, Gagan!
    print(add(5, 3))                    # 8

This is how large projects are organized — split code into multiple files, import what you need.


Import with Alias

You can give a module a shorter name:


    import datetime as dt
    import math as m

    print(dt.datetime.now())
    print(m.sqrt(16))


External Libraries — pip

Built-in modules are great but Python's real power comes from thousands of external libraries built by the community.

What is pip?

pip is Python's package manager — it downloads and installs external libraries from the internet.


Installing a Library

Open your terminal/command prompt and type:

pip install library_name

On Mac/Linux:

pip3 install library_name

Most Important Libraries to Know

requests — HTTP requests (talking to the internet)

pip install requests

    import requests

    response = requests.get("https://api.github.com/users/gagan")
    print(response.status_code)        # 200 means success
    data = response.json()             # convert response to dictionary
    print(data)

This is how Python programs talk to websites and APIs. Essential for web development.


colorama — Colored terminal output

pip install colorama

    from colorama import Fore, Back, Style, init
    init()

    print(Fore.RED + "This is red text")
    print(Fore.GREEN + "This is green text")
    print(Fore.BLUE + "This is blue text")
    print(Back.YELLOW + "Yellow background")
    print(Style.RESET_ALL + "Back to normal")


rich — Beautiful terminal output

pip install rich

    from rich.console import Console
    from rich.table import Table

    console = Console()
    console.print("[bold green]Hello[/bold green] [red]World[/red]!")

    # Beautiful table
    table = Table(title="Students")
    table.add_column("Name", style="cyan")
    table.add_column("Marks", style="magenta")
    table.add_column("Grade", style="green")

    table.add_row("Rahul", "85", "B")
    table.add_row("Priya", "92", "A")
    table.add_row("Gagan", "78", "C")

    console.print(table)


Checking Installed Libraries

pip list

Shows all installed libraries with versions.


requirements.txt — Sharing Dependencies

In real projects you list all required libraries in a file called requirements.txt:

requests==2.31.0
colorama==0.4.6
rich==13.7.0

Anyone can install all dependencies at once:

pip install -r requirements.txt

This is standard practice in every Python project.


Real World Example — Putting It All Together

A program that uses multiple modules together:


    import json
    import os
    import random
    from datetime import datetime

    USERS_FILE = "users.json"

    def load_users():
        if os.path.exists(USERS_FILE):
            with open(USERS_FILE, "r") as file:
                return json.load(file)
        return {}

    def save_users(users):
        with open(USERS_FILE, "w") as file:
            json.dump(users, file, indent=4)

    def generate_user_id():
        return random.randint(10000, 99999)

    def register_user(users):
        name = input("Enter name: ").strip()
        email = input("Enter email: ").strip().lower()

        if email in users:
            print("Email already registered!")
            return

        user_id = generate_user_id()
        joined = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

        users[email] = {
            "id": user_id,
            "name": name,
            "joined": joined
        }

        save_users(users)
        print(f"\nRegistered successfully!")
        print(f"Your User ID: {user_id}")
        print(f"Joined: {joined}")

    def view_users(users):
        if not users:
            print("No users registered yet")
            return

        print(f"\n=== All Users ({len(users)}) ===")
        for email, info in users.items():
            print(f"ID: {info['id']} | Name: {info['name']} | Email: {email} | Joined: {info['joined']}")


    users = load_users()

    while True:
        print("\n=== User Management ===")
        print("1. Register user")
        print("2. View all users")
        print("3. Exit")

        choice = input("Choice: ")

        if choice == "1":
            register_user(users)
        elif choice == "2":
            view_users(users)
        elif choice == "3":
            print("Goodbye!")
            break
        else:
            print("Invalid choice")

This uses json, os, random, and datetime all together in one real application.


Quick Reference


    # Built-in modules — no installation
    import math
    import random
    import os
    import json
    import string
    from datetime import datetime

    # External — install with pip first
    # pip install requests
    import requests

    # Import with alias
    import numpy as np         # common alias for numpy
    import pandas as pd        # common alias for pandas

    # Import specific items
    from math import sqrt, pi
    from datetime import datetime, timedelta

    # Your own module
    import helpers             # imports helpers.py from same folder


Exercise 🏋️

Build a Mini Project Manager using multiple modules:

=== Project Manager ===
1. Create new project
2. View all projects
3. Add task to project
4. Mark task complete
5. Exit

Requirements:

  • Save all data in projects.json using json module
  • Each project has: name, created date (using datetime), unique ID (using random), and list of tasks
  • Each task has: description, status (pending/complete), added date
  • Use os to check if file exists on startup

Expected JSON structure:

{
    "proj_12345": {
        "name": "Learn Python",
        "created": "2025-03-03",
        "tasks": [
            {
                "id": "task_001",
                "description": "Complete Stage 8",
                "status": "complete",
                "added": "2025-03-03"
            }
        ]
    }
}

This is a real project management app — the kind of thing you'd actually build and use!

Modules & Libraries in Python

Modules and Imports What is a Module? So far you've written everything from scratch. But Python comes with hundreds of pre-built modul...