Modules and Packages - Code Organization

A module is a Python file (.py) containing code. A package is a folder containing modules. Using modules helps: 1) Organize code logically, 2) Reuse code across projects, 3) Avoid naming conflicts, 4) Make large projects manageable. Python comes with built-in modules (standard library) and you can install external ones (pip).

# Modules and Packages examples
print("MODULES AND PACKAGES EXPLORATION")
print("=" * 50)

# Example 1: Using built-in modules
print("\n1. USING BUILT-IN MODULES")
print("-" * 25)

# Math module
import math
print("Math Module:")
print(f"Square root of 16: {math.sqrt(16)}")
print(f"Pi: {math.pi}")
print(f"Cosine of 60 degrees: {math.cos(math.radians(60)):.2f}")
print(f"Factorial of 5: {math.factorial(5)}")

# Random module
import random
print("\nRandom Module:")
print(f"Random number between 0-1: {random.random():.2f}")
print(f"Random integer 1-10: {random.randint(1, 10)}")
print(f"Random choice from list: {random.choice(['apple', 'banana', 'cherry'])}")

# Statistics module
import statistics
numbers = [85, 90, 78, 92, 88]
print("\nStatistics Module:")
print(f"Numbers: {numbers}")
print(f"Mean: {statistics.mean(numbers)}")
print(f"Median: {statistics.median(numbers)}")
print(f"Standard Deviation: {statistics.stdev(numbers):.2f}")

# Example 2: Import specific functions
print("\n\n2. SPECIFIC IMPORTS")
print("-" * 25)

# Import only what you need
from math import sqrt, pow, pi
from random import randint, choice

print("Using specific imports:")
print(f"sqrt(25) = {sqrt(25)}")
print(f"2^8 = {pow(2, 8)}")
print(f"Random 1-100: {randint(1, 100)}")

# Example 3: Aliasing modules
print("\n\n3. MODULE ALIASING")
print("-" * 25)

import datetime as dt
import numpy as np  # Common alias for numpy

print("Using aliases:")
print(f"Today: {dt.datetime.now().date()}")
print(f"Time: {dt.datetime.now().time().strftime('%H:%M')}")

# Example 4: Creating your own module
print("\n\n4. CREATING YOUR OWN MODULE")
print("-" * 25)

# First, let's create a module file (in real life, you'd save this separately)
# Create a file called 'mymodule.py' with the following content:
'''
# mymodule.py content:
"""My custom module for learning Python"""

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

def calculate_area(radius):
    """Calculate area of a circle"""
    import math
    return math.pi * radius ** 2

def is_even(number):
    """Check if number is even"""
    return number % 2 == 0

# Module-level variable
version = "1.0.0"
'''

# Now let's simulate using it (in reality, you'd import mymodule)
print("Simulating module usage:")
print("In real code, you would save the above as 'mymodule.py'")
print("Then import it: import mymodule")
print("Then use: mymodule.greet('Alice')")

# Example 5: Creating a package
print("\n\n5. CREATING A PACKAGE")
print("-" * 25)

print("Package structure example:")
print("""
my_package/
    __init__.py          # Makes folder a package
    math_utils.py        # Module 1
    string_utils.py      # Module 2
    data_processing.py   # Module 3
""")

print("\n__init__.py can be empty or contain package initialization code")
print("\nUsage in code:")
print("from my_package import math_utils")
print("from my_package.string_utils import format_name")

# Example 6: Checking available modules
print("\n\n6. EXPLORING AVAILABLE MODULES")
print("-" * 25)

import sys
print(f"Python version: {sys.version}")
print(f"\nSome built-in modules in sys.builtin_module_names:")
for i, module in enumerate(list(sys.builtin_module_names)[:10], 1):
    print(f"{i}. {module}")
print("... and many more!")

# Example 7: Installing external packages
print("\n\n7. INSTALLING EXTERNAL PACKAGES")
print("-" * 25)

print("Using pip (Python package manager):")
print("1. Open terminal/command prompt")
print("2. Type: pip install package_name")
print("\nPopular packages:")
print("- numpy: Scientific computing")
print("- pandas: Data analysis")
print("- requests: HTTP requests")
print("- flask: Web framework")
print("- matplotlib: Data visualization")

# Example 8: Virtual environments
print("\n\n8. VIRTUAL ENVIRONMENTS")
print("-" * 25)

print("Why use virtual environments?")
print("1. Isolate project dependencies")
print("2. Avoid version conflicts")
print("3. Reproducible environments")
print("\nCreating a virtual environment:")
print("python -m venv myenv          # Create")
print("source myenv/bin/activate    # Activate (Linux/Mac)")
print("myenv\\Scripts\\activate     # Activate (Windows)")
print("deactivate                   # Deactivate")

# Example 9: Complete example with custom module
print("\n\n9. COMPLETE EXAMPLE: SHOPPING CART MODULE")
print("-" * 25)

# Let's create a shopping module simulation
class ShoppingCart:
    def __init__(self):
        self.items = []
        self.prices = []
    
    def add_item(self, item, price):
        self.items.append(item)
        self.prices.append(price)
        print(f"Added: {item} - ${price:.2f}")
    
    def remove_item(self, item):
        if item in self.items:
            index = self.items.index(item)
            self.items.pop(index)
            price = self.prices.pop(index)
            print(f"Removed: {item} - ${price:.2f}")
        else:
            print(f"Item '{item}' not found in cart.")
    
    def total(self):
        return sum(self.prices)
    
    def show_cart(self):
        if not self.items:
            print("Cart is empty!")
        else:
            print("\nShopping Cart:")
            print("-" * 30)
            for item, price in zip(self.items, self.prices):
                print(f"{item:20} ${price:6.2f}")
            print("-" * 30)
            print(f"Total:{'':18} ${self.total():6.2f}")

# Create a module-like structure
print("In a file called 'shopping.py':")
print("""
# shopping.py
"""Shopping cart module"""

class ShoppingCart:
    # ... (same class definition as above)

def apply_discount(total, percentage):
    """Apply percentage discount"""
    return total * (1 - percentage/100)

def format_currency(amount):
    """Format amount as currency"""
    return f"${amount:.2f}"
""")

print("\nThen in main.py:")
print("""
# main.py
import shopping

cart = shopping.ShoppingCart()
cart.add_item("Laptop", 999.99)
cart.add_item("Mouse", 25.50)
cart.show_cart()

total = cart.total()
discounted = shopping.apply_discount(total, 10)
print(f"After 10% discount: {shopping.format_currency(discounted)}")
""")

# Example 10: Module documentation
print("\n\n10. MODULE DOCUMENTATION")
print("-" * 25)

print("Good module includes:")
print("1. Module docstring (triple quotes at top)")
print("2. Function docstrings")
print("3. Clear naming conventions")
print("4. Examples in docstrings")

print("\nExample docstring:")
print("""
"""Math Utilities Module

This module provides basic mathematical operations
and helper functions for common calculations.

Author: Your Name
Version: 1.0.0
"""

def add(a, b):
    """
    Add two numbers.
    
    Parameters:
    a (int/float): First number
    b (int/float): Second number
    
    Returns:
    int/float: Sum of a and b
    
    Example:
    >>> add(5, 3)
    8
    >>> add(2.5, 1.5)
    4.0
    """
    return a + b
""")