Modules and the standard library
As programs grow, you split them into modules: files of related code you can import. Python also ships with a huge standard library ("batteries included"), and hundreds of thousands of third-party packages on PyPI.
Importing
| Style | When to use |
|---|---|
import math |
The default: clear where each name comes from (math.sqrt) |
from math import sqrt |
When you use a few names often |
import numpy as np |
Long names with a well-known alias |
from math import * |
❌ Avoid: you can't tell where names come from |
Your own modules
Any .py file is a module. Imagine a project like this:
shop/
├── main.py
└── pricing.py# pricing.py
TAX_RATE = 0.18
def with_tax(price):
return round(price * (1 + TAX_RATE), 2)# main.py
from pricing import with_tax
print(with_tax(100)) # 118.0Run it with python main.py. A folder of modules with an __init__.py file is a package: from shop.pricing import with_tax.
if name == "main"
When you run a file, its __name__ is "__main__". When it's imported, __name__ is the module's name. This lets a file be both a reusable module and a runnable script:
A tour of the standard library
random
datetime
collections
itertools and functools
re: regular expressions
More you'll use
| Module | For |
|---|---|
os, pathlib, shutil |
Files, folders, environment variables |
sys |
Command-line arguments, the Python version |
json, csv, sqlite3 |
Data formats and a built-in database |
logging |
Proper log messages instead of print |
argparse |
Command-line tools with --flags |
urllib, http |
Basic web requests (most people use requests or httpx) |
subprocess |
Run other programs |
unittest |
Testing (next lessons) |
Third-party packages
Beyond the standard library, PyPI (pypi.org) hosts packages for nearly everything. You install them with pip, inside a virtual environment (covered in the last lesson):
pip install requestsimport requests
response = requests.get("https://api.github.com/repos/python/cpython")
print(response.json()["stargazers_count"])Popular ones: requests/httpx (HTTP), pandas (data), numpy (maths), matplotlib (charts), fastapi/django/flask (web), pytest (testing), rich (pretty terminal output).
Practice
- Use
randomto simulate rolling two dice 1,000 times, and count how often each total (2 to 12) appears with aCounter. - Use
datetimeto print what weekday you were born on. - Use
reto extract all the hashtags from"Loving #python and #coding today! #100DaysOfCode".
1.When is __name__ == "__main__" true?
2.Why avoid from module import *?
3.Which standard-library module gives you a dict with automatic default values?