PART 1 · PYTHON FROM ZERO · LESSON 16
Modules, packages and pip
FreeLesson 18 of 78
Nobody writes everything from scratch. A module is a file of ready-made code you import; pip installs other people's modules.
import math
import random
from datetime import date, timedelta
import statistics as st # a shorter nickname
print(math.sqrt(144), math.ceil(4.2), math.floor(4.8))
random.seed(1) # same numbers every run
print(random.randint(1, 6), random.choice(["Pune", "Delhi"]))
print(date(2025, 4, 1) + timedelta(days=30))
print(st.mean([1198, 796, 1499]), st.median([1198, 796, 1499]))Output
12.0 5 4 2 Pune 2025-05-01 1164.3333333333333 1198
import pathlib
pathlib.Path("helpers.py").write_text(
"def clean(s):\n"
" return s.strip().lower()\n\n"
"STATUSES = {'delivered', 'cancelled', 'returned'}\n")
import helpers # your file is a module
print(helpers.clean(" DELIVERED "), helpers.STATUSES)Output
delivered {'delivered', 'returned', 'cancelled'}Any .py file in the same folder can be imported by its name. This snippet writes helpers.py first, then imports it. Real projects split code into modules like extract.py, transform.py and load.py.
# inside your activated .venv (Lesson 1)
pip install pandas requests # get packages
pip list # what is installed
pip freeze > requirements.txt # save versions
pip install -r requirements.txt # on another machine| Module | Use it for | Pages |
|---|---|---|
csv, json, pathlib | Reading and writing files | 33 |
datetime, zoneinfo | Dates and time zones | 27 |
collections | Counter, defaultdict, deque | 29, 36 |
itertools, functools | Iteration and function tools | 36 |
re | Patterns in text, log parsing | 64 |
pandas | Tables (pip install) | 69, 70 |
import pathlib, subprocess, sys
pathlib.Path("tool.py").write_text(
"def main():\n"
" print('running the tool')\n\n"
"if __name__ == '__main__':\n"
" main()\n")
import tool # importing: main() does not run
print("imported; its __name__ is", tool.__name__)
run = subprocess.run([sys.executable, "tool.py"],
capture_output=True, text=True)
print("run directly:", run.stdout.strip())Output
imported; its __name__ is tool run directly: running the tool
A file can be both a module you import and a program you run. Code under the __main__ check runs only when you execute the file, not when another file imports it. Every pipeline script uses this.
Try it yourself before moving on
- Print math.pi rounded to 3 decimals.
- Find the weekday name of 2025-04-01 with datetime (strftime("%A")).
- Create utils.py with one function, then import and call it.