13

Day 13: Modules and Packages

Chapter 13 • Intermediate

40 min

Modules and packages help you organize your Python code into reusable components. They make your code more manageable and allow you to use code written by others.

What are Modules?

A module is a file containing Python code. It can define functions, classes, and variables that you can use in other Python files.

What are Packages?

A package is a collection of modules organized in directories. It's like a folder containing multiple Python files.

Modules and Packages

  • Module - A single Python file
  • Package - A directory containing modules
  • Import - Bring modules into your code
  • Standard Library - Built-in modules that come with Python
  • Third-party Packages - Modules created by the community
  • pip - Package installer for Python

Common Modules:

  • math - Mathematical functions
  • random - Random number generation
  • datetime - Date and time handling
  • os - Operating system interface
  • sys - System-specific parameters
  • json - JSON data handling

Benefits:

  • Code Organization - Keep related code together
  • Reusability - Use code in multiple projects
  • Collaboration - Share code with others
  • Maintenance - Easier to update and fix

Hands-on Examples

Using Modules

# Import entire module
import math
import random
import datetime

# Use math module
print("Square root of 16:", math.sqrt(16))
print("Pi value:", math.pi)
print("Ceiling of 4.3:", math.ceil(4.3))

# Use random module
print("Random number:", random.randint(1, 10))
print("Random choice:", random.choice(['apple', 'banana', 'cherry']))

# Use datetime module
now = datetime.datetime.now()
print("Current time:", now)
print("Today's date:", now.date())
print("Current year:", now.year)

# Import specific functions
from math import sqrt, pow
print("Square root using sqrt:", sqrt(25))
print("Power using pow:", pow(2, 3))

This example shows how to import and use Python modules. We use math for calculations, random for random numbers, and datetime for date/time operations.