TOPIC 4: Functions & Code Documentation

5. Modules in Python

A module in Python is a file containing Python code (functions, classes, and variables). It allows you to organize your code and reuse it across different programs.

  • Importing a Module: To use a module, you can import it using the import statement.
import math
print(math.sqrt(16))  # Output: 4.0
  • Import Specific Functions: You can import specific functions from a module:
from math import sqrt
print(sqrt(16))  # Output: 4.0

Using the datetime Module

  • Converting String to Date: To convert the task deadline from a string to a datetime object, we use the datetime.strptime() method.
from datetime import datetime
deadline = "2025-03-22"
deadline_date = datetime.strptime(deadline, "%Y-%m-%d")
print(deadline_date)  # Output: 2025-03-22 00:00:00
  • Comparing Dates: To check if a task's deadline is approaching, we can compare dates like this:
from datetime import datetime
deadline_date = datetime(2025, 3, 22)
today = datetime.now()

if (deadline_date - today).days <= 2:
    print("Task is due soon!")