Imports and Standard-Library Modules
Unit ID: M05-U06 Estimated active time: 22-30 minutes
A module groups reusable Python code
Python's standard library provides modules installed with Python.
import math
planned_minutes = 225
planned_hours = math.ceil(planned_minutes / 60)
print(planned_hours)
math.ceil() rounds upward, producing 4.
The module name keeps provenance visible. A reader can see that ceil comes from math.
Import one name deliberately
from statistics import mean
average = mean([8, 12, 4])
This is concise, but the origin is less visible at the call. Use the style that matches the codebase and avoids name conflicts.
Aliases
Libraries often use established aliases:
import statistics as stats
print(stats.mean([8, 12, 4]))
Do not invent cryptic aliases merely to save typing.
Avoid wildcard imports
from math import *
This brings many names into the current namespace and makes origins unclear. Prefer explicit imports.
Your own module
If course_tools.py contains:
def clean_status(raw_status: str) -> str:
return raw_status.strip().lower()
Another file in the same project may use:
from course_tools import clean_status
Notebook import behaviour depends on the current working directory and Python path. The course package will provide a fixed folder structure.
Import should not run a report unexpectedly
Keep demonstration code under:
if __name__ == "__main__":
print("Run a direct demonstration here")
When imported, __name__ is the module name and the demonstration is skipped. When run directly, __name__ is "__main__".
Practice
Use statistics.mean() to calculate the average of [8, 12, 4]. Inspect help(statistics.mean). Then import the same function directly and compare readability.
Takeaway
Modules group reusable code. Use explicit imports, clear provenance, and a main guard so import does not trigger unrelated output. Next, we will distinguish modules from installed packages and isolated environments.
