Cohort 4Register

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.

THE STANDARD LIBRARY: ALREADY INSTALLEDPYTHON 3.12
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
YOUR OWN MODULEPYTHON 3.12
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.

PIP IN THE TERMINALTERMINAL · NOT RUN
# 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
ModuleUse it forPages
csv, json, pathlibReading and writing files33
datetime, zoneinfoDates and time zones27
collectionsCounter, defaultdict, deque29, 36
itertools, functoolsIteration and function tools36
rePatterns in text, log parsing64
pandasTables (pip install)69, 70
IF __NAME__ == "__MAIN__": RUN ONLY WHEN EXECUTEDPYTHON 3.12
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

  1. Print math.pi rounded to 3 decimals.
  2. Find the weekday name of 2025-04-01 with datetime (strftime("%A")).
  3. Create utils.py with one function, then import and call it.