Part 3: Python Programming

11. Modules & the Standard Library

Modules & the Standard Library

No one writes every program from scratch. Python comes with a huge standard library of ready-made code, grouped into modules. A module is simply a file of Python definitions you can bring into your program. This chapter shows how to import modules, tours a few useful ones, and explains how to install extra packages.

Import forms

There are three common ways to import. The first brings in the whole module; you then use its contents with a dot. The second imports specific names directly. The third renames a module to a shorter alias:

PYTHON
import math
print(math.sqrt(25))

from math import sqrt, pi
print(sqrt(25), pi)

import statistics as st
print(st.mean([2, 4, 6]))
▸ OUTPUT
5.0
5.0 3.141592653589793
4

Prefer import math over from math import * (which imports everything): keeping the module name makes it obvious where a function came from.

The random module

The random module produces random numbers and choices, perfect for games and simulations. (Your exact numbers will differ each run because they are random.)

PYTHON
import random

print(random.randint(1, 6))
print(random.choice(["red", "green", "blue"]))

cards = [1, 2, 3, 4, 5]
random.shuffle(cards)
print(cards)
▸ OUTPUT (example, varies each run)
4
green
[3, 1, 5, 2, 4]

randint(1, 6) returns a whole number between 1 and 6 inclusive, like rolling a die. choice picks one item from a list, and shuffle rearranges a list in place.

The datetime module

The datetime module works with dates and times. Here we get today's date and format it nicely:

PYTHON
from datetime import date

today = date(2024, 10, 21)
print(today)
print(today.year)
print(today.strftime("%d %B %Y"))
▸ OUTPUT
2024-10-21
2024
21 October 2024

In a real program you would call date.today() to get the current date automatically. The strftime method turns a date into text using format codes such as %Y for the four-digit year and %B for the month name.

pip and third-party packages

Beyond the standard library, the community has published hundreds of thousands of free packages on the Python Package Index (PyPI). You install them with pip, Python's package installer, from your terminal (not inside a Python script):

PYTHON
pip install requests

Once installed, you import it just like a standard module:

PYTHON
import requests
# response = requests.get("https://example.com")
# print(response.status_code)

Popular packages include requests for web requests, pandas for data analysis, and pygame for games. Installing packages per project, inside a virtual environment, is a good habit you will learn as you progress.

Splitting your own code into modules

Any .py file you write is itself a module that other files can import. Suppose you save this as tools.py:

PYTHON
# tools.py
def double(n):
    return n * 2

Then in another file in the same folder you can use it:

PYTHON
# main.py
import tools
print(tools.double(21))
▸ OUTPUT
42

Splitting code into modules keeps each file focused and lets you reuse your work across projects. As your programs grow, organising them into several small modules is far easier to manage than one enormous file.

The standard library is sometimes called "batteries included" because so much is ready to use. Whenever you face a common task, search the documentation first; the tool you need may already exist.