Modules and Packages
15 min In ProgressLearning Objectives
- Import built-in and custom modules
- Use from...import syntax
- Explore module contents with dir()
Importing Modules
Use import to bring in code from other files or the standard library.
import math
print(math.pi)
print(math.sqrt(16))
Selective Imports
Import only what you need to keep namespaces clean.
from random import randint, choice
print(randint(1, 6))
print(choice(["apple", "banana", "cherry"]))
Course Example: Package Enumerator
List all resources defined in a module using dir().
import math
resources = dir(math)
for resource in resources:
print(resource)
📝 Exercise: Date Formatter
Import datetime and print the current date in YYYY-MM-DD format.
code.py
Output