πŸ“š
CodingπŸŽ“ Ages 14-18Beginner 13 min read

Using Python Libraries (modules)

Learn how Python libraries and modules work: import the standard library, use math, random, datetime and statistics, pick the right import style, and install third-party packages with pip. Runnable code, a worked program and a quiz.

Key takeaways

  • A module is a file of ready-made Python code; a library is a collection of modules you can reuse
  • import brings a module in; you then use its tools as module.name, like math.sqrt(9)
  • from module import name pulls one tool out so you can call it directly, and 'as' gives it a short alias
  • Python ships with a huge standard library (math, random, datetime, statistics, json and more) β€” no install needed
  • Third-party libraries are installed from PyPI with pip, e.g. pip install requests

Standing on the shoulders of giants

Imagine needing a square root, the current date, or a way to shuffle a deck β€” and having to write all that maths from scratch every time. You don't. Other programmers have already written, tested, and polished that code, packaged it into modules and libraries, and made it available for you to import. Learning to use libraries is one of the biggest leaps from "writing toy programs" to "building real things."

This lesson assumes you can write your first Python program and understand functions and parameters. Let's unlock the toolbox.

What is a module?

A module is simply a file of Python code β€” functions, values and classes β€” that someone wrote so it can be reused. A library is a collection of such modules grouped around a theme. Python comes with an enormous standard library of modules built right in, ready to use without installing anything.

You bring a module into your program with the import statement, usually at the very top of the file.

The plain import

The most basic form imports the whole module. You then reach its tools through the module's name:

import math

print(math.sqrt(16))    # 4.0
print(math.pi)          # 3.141592653589793
print(math.floor(4.7))  # 4

import math loads the module. math.sqrt, math.pi and math.floor are tools inside it, so we write math. before each. This dotted style is clear: anyone reading math.sqrt instantly knows where sqrt came from.

The from-import form

If you only need one or two tools, from module import name pulls them out so you can use them without the module prefix:

from random import randint, choice

print(randint(1, 6))               # e.g. 4
print(choice(["red", "green"]))    # e.g. "green"

Now randint and choice are available directly. This is tidier for a couple of names, but be careful: if you import too many things this way, it can get hard to tell where each name came from.

Aliases with as

Some library names are long, or have a community-standard short form. The keyword as gives a module (or imported name) an alias:

import statistics as stats

data = [4, 8, 15, 16, 23, 42]
print(stats.mean(data))     # 18
print(stats.median(data))   # 15.5

You'll see this constantly in data work: import numpy as np and import pandas as pd are near-universal conventions. The alias is just a nickname you choose (or that the community has agreed on).

A tour of the standard library

Python's standard library is huge. Here are four modules you'll meet early:

math β€” advanced arithmetic: sqrt, pi, floor, ceil, pow, trig functions.

random β€” randomness for games and sampling: randint, choice, shuffle, random.

datetime β€” dates and times:

from datetime import date

today = date.today()
print("Today is", today)              # e.g. 2026-05-30
print("The year is", today.year)      # 2026

statistics β€” averages and spread: mean, median, mode, stdev.

Because these ship with Python, you can import them on any computer with Python installed β€” nothing to download.

Beyond the standard library: pip and PyPI

The standard library is big, but the wider world of Python is bigger still. Tens of thousands of third-party libraries live on PyPI, the Python Package Index. You install them with pip, Python's package installer, by running a command in your terminal (not inside your program):

pip install requests

After installing, you import and use it like any other module:

import requests

response = requests.get("https://example.com")
print(response.status_code)   # 200 if the page loaded

Famous third-party libraries include requests (web requests), numpy and pandas (data and maths), matplotlib (charts), and pygame (games). Each saves you days of work.

Worked example: a quick stats report

Let's combine several standard-library modules into one small program that invents some test data, then describes it. It uses random to make data, statistics to summarise it, and datetime to time-stamp the report.

import random
import statistics
from datetime import date

def make_sample(count, low, high):
    """Return a list of 'count' random integers between low and high."""
    return [random.randint(low, high) for _ in range(count)]

def describe(numbers):
    """Return a dict summarising a list of numbers."""
    return {
        "count": len(numbers),
        "min": min(numbers),
        "max": max(numbers),
        "mean": round(statistics.mean(numbers), 1),
        "median": statistics.median(numbers),
    }

def print_report(numbers):
    summary = describe(numbers)
    print(f"Report for {date.today()}")
    print("-" * 24)
    for label, value in summary.items():
        print(f"{label:>7}: {value}")

# Run it
random.seed(1)                      # same numbers each run, for testing
sample = make_sample(20, 1, 100)
print("Sample:", sample)
print_report(sample)

How it works:

  1. make_sample uses a list comprehension with random.randint to build a list of 20 random numbers. The _ is a throwaway loop variable β€” we don't need its value, only the repetition.
  2. describe leans on built-ins (min, max, len) and the statistics module (mean, median) to produce a summary dictionary. We round the mean for neatness.
  3. print_report stamps the report with today's date from datetime, then loops over the summary. The {label:>7} format aligns the labels to the right in a 7-character column for a tidy table.
  4. random.seed(1) makes the "random" data the same every run, which is invaluable while testing. Remove it for genuine variety.

In about 30 lines, three different libraries cooperate β€” that's the everyday reality of real Python.

Try it yourself

Build your own multi-library tool:

  • Use random.choice to pick a random operation ("+", "-", "*") and random.randint to pick two numbers, then print the sum as a quick mental-maths quiz.
  • Use the time module: import time, then time.sleep(1) to pause one second between questions, building suspense.
  • Use statistics.mean to report the player's average answer time if you record how long each answer takes (hint: time.time() gives the current time in seconds).
  • Challenge: explore the json module β€” import json, then json.dumps(your_dict) turns a dictionary into a text string you could save to a file.

Once you're fluent with libraries, whole project genres open up. To put one to work in a game, head to a text adventure game in Python and try using random to add surprises.

Quick quiz

Test yourself and earn XP

What is a Python module?

After import math, how do you call its square-root function?

What does `from random import randint` let you do?

Which tool installs third-party libraries from PyPI?

Why does `import numpy as np` use `as np`?

FAQ

A module is a single .py file of code. A package is a folder of related modules bundled together. A library is the general word for reusable code you import, and people use it loosely for both modules and packages. In everyday talk the three terms overlap; the key idea is the same: someone wrote useful code so you do not have to.

Mostly yes β€” popular packages on PyPI (the Python Package Index) are widely used and trusted. But anyone can publish a package, so check the name spelling carefully (typo-squatting is a real trick), prefer well-known libraries with many downloads, and read the docs. On shared machines, install into a virtual environment so projects stay isolated from each other.