Courses/Python/Modules and Packages

    Lesson 11 • Intermediate

    Modules and Packages

    Organize your code, reuse functionality, and explore Python's powerful built-in libraries.

    What You'll Learn in This Lesson

    • What modules are and how they keep code organized
    • All 4 ways to import: import x, from x import y, as alias, *
    • The math module: sqrt, ceil, floor, pow, pi
    • The random module: random numbers, choices, shuffle
    • The datetime module: dates, times, formatting
    • How to install external packages with pip

    What Are Modules?

    A module is simply a Python file (.py) that contains code you can reuse. Instead of writing everything in one file, you split your code into organized pieces.

    TermWhat It IsExample
    ModuleA single .py filemath.py, helpers.py
    PackageA folder of modulesmy_app/ folder
    LibraryCollection of packagesrequests, numpy

    Why Use Modules?

    BenefitDescription
    ReusabilityWrite once, use everywhere
    OrganizationKeep related code together
    MaintainabilityEasier to find and fix bugs
    CollaborationTeams can work on different files

    Importing Modules

    Use the import keyword to use a module:

    StyleSyntaxUsage
    Import whole moduleimport mathmath.sqrt(16)
    Import specific itemfrom math import sqrtsqrt(16)
    Import with aliasimport math as mm.sqrt(16)
    Import multiplefrom math import sqrt, pisqrt(16), pi

    Import Styles

    Different ways to import modules

    Try it Yourself »
    Python
    # Different ways to import
    import math
    print("Using import math:")
    print(f"  math.sqrt(25) = {math.sqrt(25)}")
    print(f"  math.pi = {math.pi:.4f}")
    
    from math import sqrt, ceil
    print("\nUsing from math import sqrt, ceil:")
    print(f"  sqrt(49) = {sqrt(49)}")
    print(f"  ceil(4.2) = {ceil(4.2)}")
    
    import datetime as dt
    print("\nUsing import datetime as dt:")
    print(f"  Today: {dt.date.today()}")

    The math Module

    Python's built-in math module provides mathematical functions:

    FunctionWhat It DoesExample
    math.sqrt(x)Square rootsqrt(16) → 4.0
    math.ceil(x)Round upceil(4.2) → 5
    math.floor(x)Round downfloor(4.8) → 4
    math.pow(x, y)x to the power of ypow(2, 3) → 8.0
    math.piPi constant3.14159...

    Math Module

    Mathematical operations

    Try it Yourself »
    Python
    import math
    
    print("=== Math Module ===")
    print(f"Square root of 64: {math.sqrt(64)}")
    print(f"2 to the power of 10: {math.pow(2, 10)}")
    print(f"Ceiling of 3.2: {math.ceil(3.2)}")
    print(f"Floor of 3.8: {math.floor(3.8)}")
    print(f"Pi: {math.pi:.6f}")
    print(f"Factorial of 5: {math.factorial(5)}")

    The random Module

    Generate random numbers for games, testing, or simulations:

    FunctionWhat It Does
    random.randint(a, b)Random integer from a to b (inclusive)
    random.random()Random float between 0 and 1
    random.choice(list)Pick one random item
    random.shuffle(list)Shuffle list in place
    random.sample(list, n)Pick n random items

    Random Module

    Generate random values

    Try it Yourself »
    Python
    import random
    
    print("=== Random Module ===")
    print(f"Random number 1-100: {random.randint(1, 100)}")
    print(f"Random decimal: {random.random():.4f}")
    
    colors = ["red", "blue", "green", "yellow"]
    print(f"Random color: {random.choice(colors)}")
    
    numbers = [1, 2, 3, 4, 5]
    random.shuffle(numbers)
    print(f"Shuffled: {numbers}")
    
    print(f"Pick 2 colors: {random.sample(colors, 2)}")

    The datetime Module

    Work with dates and times:

    Datetime Module

    Work with dates and times

    Try it Yourself »
    Python
    from datetime import datetime, date, timedelta
    
    # Current date and time
    now = datetime.now()
    print("=== Datetime Module ===")
    print(f"Now: {now}")
    print(f"Date only: {date.today()}")
    print(f"Year: {now.year}, Month: {now.month}, Day: {now.day}")
    
    # Formatting dates
    print(f"\nFormatted: {now.strftime('%B %d, %Y')}")
    print(f"Time: {now.strftime('%H:%M:%S')}")
    
    # Date math
    tomorrow = date.today() + timedelta(days=1)
    next_week = date.today() + timedelta(weeks=1)
    print(f"\nTomorrow: {tomorrow}")
    prin
    ...

    The os Module

    Interact with your computer's operating system:

    OS Module

    System operations

    Try it Yourself »
    Python
    import os
    
    print("=== OS Module ===")
    print(f"Current directory: {os.getcwd()}")
    print(f"Operating system: {os.name}")
    
    # Path operations (works on any OS)
    path = os.path.join("folder", "subfolder", "file.txt")
    print(f"\nJoined path: {path}")
    print(f"File name: {os.path.basename(path)}")
    print(f"Directory: {os.path.dirname(path)}")
    
    # Check if path exists
    print(f"\nCurrent dir exists: {os.path.exists('.')}")

    The json Module

    JSON (JavaScript Object Notation) is a universal format for storing and exchanging data. It's used by almost every API.

    FunctionWhat It Does
    json.dumps(obj)Convert Python → JSON string
    json.loads(string)Convert JSON string → Python
    json.dump(obj, file)Write Python to JSON file
    json.load(file)Read JSON file to Python

    JSON Module

    Work with JSON data

    Try it Yourself »
    Python
    import json
    
    # Python dictionary
    user = {
        "name": "Alice",
        "age": 25,
        "is_student": True,
        "skills": ["Python", "JavaScript"]
    }
    
    # Convert to JSON string
    json_string = json.dumps(user, indent=2)
    print("=== Python to JSON ===")
    print(json_string)
    
    # Convert back to Python
    parsed = json.loads(json_string)
    print(f"\n=== Back to Python ===")
    print(f"Name: {parsed['name']}")
    print(f"Skills: {parsed['skills']}")

    Creating Your Own Module

    Any Python file can be a module. Just save your code and import it:

    Step 1: Create helpers.py

    # helpers.py
    def greet(name):
        return f"Hello, {name}!"
    
    def add(a, b):
        return a + b

    Step 2: Import in another file

    # main.py
    import helpers
    
    print(helpers.greet("World"))
    print(helpers.add(5, 3))

    Custom Module

    Create your own reusable code

    Try it Yourself »
    Python
    # Simulating a custom module
    
    # This would be in my_helpers.py:
    def greet(name):
        return f"Hello, {name}!"
    
    def calculate_area(length, width):
        return length * width
    
    PI = 3.14159
    
    # Using the "module":
    print(greet("Python Learner"))
    print(f"Area: {calculate_area(5, 3)}")
    print(f"PI value: {PI}")

    Understanding Packages

    A package is a folder containing multiple modules. It must have an __init__.py file (can be empty).

    my_package/
        __init__.py      ← Makes it a package
        greetings.py     ← Module 1
        math_utils.py    ← Module 2
        helpers.py       ← Module 3

    Importing from packages:

    from my_package import greetings
    from my_package.math_utils import calculate
    import my_package.helpers as h

    Installing External Packages with pip

    pip is Python's package manager. It downloads packages from PyPI (Python Package Index) — a library of over 400,000 packages!

    CommandWhat It Does
    pip install requestsInstall a package
    pip uninstall requestsRemove a package
    pip listShow installed packages
    pip freezeList packages with versions

    Popular packages to try:

    • requests — make HTTP requests to APIs
    • flask — build web applications
    • pandas — data analysis
    • pygame — create games

    Common Mistakes to Avoid

    MistakeProblemFix
    from math import *Can overwrite your variablesfrom math import sqrt
    Naming file same as modulemath.py shadows built-in mathUse unique file names
    Circular importsA imports B, B imports ARestructure your code
    Forgetting __init__.pyFolder not recognized as packageAdd empty __init__.py

    Practical Example: Password Generator

    Use multiple modules to create a random password generator:

    Password Generator

    Combine random and string modules

    Try it Yourself »
    Python
    import random
    import string
    
    def generate_password(length=12):
        """Generate a secure random password."""
        # All possible characters
        characters = string.ascii_letters + string.digits + "!@#$%"
        
        # Generate password
        password = ''.join(random.choice(characters) for _ in range(length))
        return password
    
    # Generate passwords of different lengths
    print("=== Password Generator ===")
    print(f"8 chars:  {generate_password(8)}")
    print(f"12 chars: {generate_password(12)}")
    print(f"16
    ...

    Practical Example: Date Calculator

    Calculate days between dates and future dates:

    Date Calculator

    Work with dates

    Try it Yourself »
    Python
    from datetime import datetime, date, timedelta
    
    def days_until(target_date):
        """Calculate days until a target date."""
        today = date.today()
        target = datetime.strptime(target_date, "%Y-%m-%d").date()
        delta = target - today
        return delta.days
    
    def add_days(start_date, days):
        """Add days to a date."""
        start = datetime.strptime(start_date, "%Y-%m-%d").date()
        result = start + timedelta(days=days)
        return result.strftime("%B %d, %Y")
    
    # Examples
    print("=== Date Calcul
    ...

    Practical Example: Data Analyzer

    Use json and math to analyze data:

    Data Analyzer

    Analyze JSON data

    Try it Yourself »
    Python
    import json
    import math
    
    # Sample data (could come from a file or API)
    data_json = '''
    {
        "students": [
            {"name": "Alice", "score": 85},
            {"name": "Bob", "score": 92},
            {"name": "Charlie", "score": 78},
            {"name": "Diana", "score": 95}
        ]
    }
    '''
    
    # Parse JSON
    data = json.loads(data_json)
    scores = [s["score"] for s in data["students"]]
    
    # Calculate statistics
    average = sum(scores) / len(scores)
    highest = max(scores)
    lowest = min(scores)
    
    print("=== Student Score An
    ...

    Summary: Quick Reference

    ConceptDescriptionExample
    import xImport whole moduleimport math
    from x import yImport specific itemfrom math import sqrt
    import x as yImport with aliasimport pandas as pd
    pip install xInstall packagepip install requests

    Key Built-in Modules:

    • math — mathematical functions
    • random — random number generation
    • datetime — dates and times
    • os — operating system interaction
    • json — JSON data handling
    • string — string constants and utilities

    What's Next?

    You now know how to organize your code into reusable modules, use Python's powerful standard library, and install external packages. This is how professional developers work!

    Next up: Lesson 12 – Object-Oriented Programming — Learn to create classes and objects to model real-world concepts in your code.

    🎉

    🏅 Intermediate Track Complete! You now code like a real developer!

    Functions, Lists, Dictionaries, File Handling, Exceptions, Modules — you've completed all 11 beginner and intermediate lessons. You now have the full Python toolkit that powers real applications.

    🚀 Up next: Object-Oriented Programming — learn to model real-world things as classes and objects, the way all major software is built.

    Sign up for free to track which lessons you've completed and get learning reminders.

    Previous

    Cookie & Privacy Settings

    We use cookies to improve your experience, analyze traffic, and show personalized ads. You can manage your preferences below.

    By clicking "Accept All", you consent to our use of cookies for analytics and personalized advertising. You can customize your preferences or reject non-essential cookies.

    Privacy PolicyTerms of Service