šŸ

Modules and Packages

Intermediate
90 XP
40 min
Lesson Content

Modules and Packages: Organizing Code

Modules and packages help organize code into reusable, maintainable units. Python's standard library and third-party packages make it incredibly powerful.

What are Modules?

A module is a Python file containing functions, classes, and variables. You can import and use them in other files.

Creating and Using Modules

# math_utils.py (module file)
def add(a, b):
    return a + b

def multiply(a, b):
    return a * b

# main.py (using the module)
import math_utils

result = math_utils.add(5, 3)  # 8
print(result)

Import Methods

# Import entire module
import math
print(math.pi)  # 3.14159...

# Import specific items from math import pi, sqrt print(pi) print(sqrt(16)) # 4.0
# Import with alias import numpy as np import pandas as pd
# Import all (not recommended) from math import * print(pi) # No need for math. prefix

Standard Library Modules

Python comes with many built-in modules:

# datetime - work with dates and times
from datetime import datetime, timedelta
now = datetime.now()
tomorrow = now + timedelta(days=1)

# random - generate random numbers import random number = random.randint(1, 10) choice = random.choice(["apple", "banana", "orange"])
# os - operating system interface import os current_dir = os.getcwd() files = os.listdir('.')
# json - work with JSON data import json data = {"name": "Alice"} json_str = json.dumps(data) parsed = json.loads(json_str)

Packages

Packages are directories containing multiple modules:

# mypackage/
#   __init__.py
#   module1.py
#   module2.py

# Import from package from mypackage import module1 from mypackage.module2 import function_name

Installing Third-Party Packages

# Using pip (Python package installer)
# pip install requests
# pip install numpy pandas

# Then use in code import requests response = requests.get('https://api.example.com/data')
import numpy as np array = np.array([1, 2, 3, 4, 5])

Best Practices

  • āœ… Use descriptive module names
  • āœ… Group related functionality
  • āœ… Use __init__.py for packages
  • āœ… Document your modules with docstrings
  • āœ… Avoid circular imports
Example Code

Practice using Python's built-in modules.

import math
import random
from datetime import datetime

# Use math module
print(f"Pi: {math.pi}")
print(f"Square root of 16: {math.sqrt(16)}")

# Use random module
random_num = random.randint(1, 100)
print(f"Random number: {random_num}")

# Use datetime
now = datetime.now()
print(f"Current time: {now.strftime('%Y-%m-%d %H:%M:%S')}")

Expected Output:

Pi: 3.141592653589793
Square root of 16: 4.0
Random number: [varies]
Current time: [current datetime]
Study Tips
  • •Read the theory content thoroughly before practicing
  • •Review the example code to understand key concepts
  • •Proceed to the Practice tab when you're ready to code