I1 · Python Programming for AI

Modules and Libraries

A module is a Python file of functions and values that other programs can import. A library or package is a collection of modules. Python's standard library comes built in, with modules such as math, random and datetime; third-party packages such as NumPy are installed with pip.

10 min Intermediate · Sublevel Beginner Jump to the activity

What you need: The earlier topics of this module.

Definition

Why rewrite what someone has already written and tested?

A module is a Python file of functions and values that other programs can import. A library or package is a collection of modules. Python's standard library comes built in, with modules such as math, random and datetime; third-party packages such as NumPy are installed with pip.

In simple words

import math gives you a toolbox: math.sqrt(16) is 4.0 and math.pi is 3.14159…. import random lets you roll dice. You can import just one tool, from math import sqrt, or give a module a short name, import numpy as np. On your own computer, pip install numpy downloads a package.

Overview

  • A module is a .py file of functions, classes and variables that other programs can import.
  • A package is a folder of modules; a library is a collection of packages for a purpose.
  • import loads a module once and gives access to its contents with a dot: math.sqrt(16).
  • Python's standard library comes with Python; third-party libraries are installed with pip.
  • help(module) and dir(module) show what a module contains.
  • Most AI work uses libraries rather than writing algorithms from scratch.

Why it matters

Nobody builds AI from nothing. Libraries such as NumPy, pandas, scikit-learn and PyTorch hold years of expert work. Knowing how to import and read a library's documentation is a core skill.

Key terms

Module
A Python file whose functions and values can be imported.
Package
A folder of related modules distributed together.
Standard library
The modules that come with Python, such as math, random and datetime.
Third-party package
A package written by others and installed with pip, such as NumPy.
Alias
A short name given at import, as in import numpy as np.
Namespace
A separate space of names, so math.sqrt and another sqrt do not clash.

Types

Code you import comes from different sources, and there are several ways to write the import itself. These are the types.

1. Standard-library modules

Modules shipped with every Python installation, such as math, random, datetime, statistics, csv, json, os and collections.

  • How it works: They are always available offline; import math and call math.sqrt(), or import random and call random.choice().
  • Example: random.randint(1, 6) simulates a dice throw; datetime.date.today() gives today's date.
  • When to use it: Use them first for common tasks: Python is said to come with "batteries included".

2. Third-party libraries

Packages written by others and installed from the Python Package Index with pip.

  • How it works: pip install numpy downloads the package; then import numpy as np works like any module.
  • Example: NumPy for arrays, pandas for tables, matplotlib for charts, scikit-learn for machine learning, PyTorch for deep learning.
  • When to use it: Use well-known, maintained libraries for specialised work, and record their versions in requirements.txt.

3. Your own modules

A .py file you write and import from another file in the same folder.

  • How it works: Saving functions in helpers.py lets main.py write import helpers or from helpers import average.
  • Example: A grades.py module with grade() used by both a report program and a quiz program.
  • When to use it: Use them to split a growing program into tidy files and to reuse code across projects.

4. Packages

Folders of related modules, often with an __init__.py file, imported with dotted names.

  • How it works: Each sub-folder is a sub-package; from sklearn.linear_model import LinearRegression reaches a class inside nested folders.
  • Example: sklearn.model_selection, sklearn.metrics and sklearn.ensemble are parts of the scikit-learn package.
  • When to use it: Use packages to organise large projects; recognise their dotted names when reading documentation.

5. Import styles

import module, import module as alias, from module import name, and from module import *.

  • How it works: The first keeps the module name as a prefix; as gives a short alias; from brings chosen names in directly; * brings everything and can hide your own names.
  • Example: import pandas as pd; from math import sqrt, pi.
  • When to use it: Use the standard aliases (np, pd, plt), import only what you need, and avoid import * in real programs.

Explained in detail

Batteries included

Python is often described as "batteries included" because its standard library covers so much: math for square roots and trigonometry, random for random numbers, statistics for mean and median, datetime for dates, json and csv for data formats, os and pathlib for files and folders, collections for Counter and deque, and many more. Before writing something yourself, it is worth checking whether the standard library already does it, well tested and documented.

Ways to import

FormUse asWhen
import mathmath.sqrt(16)Clear where each name comes from; the usual choice
import numpy as npnp.array([1, 2])Long names with a community convention: np, pd, plt
from math import sqrt, pisqrt(16)A few names used often
from math import *sqrt(16)Avoid: it floods your namespace and hides where names came from

The AI library stack

Most AI work in Python rests on a small set of third-party packages, each built on the one before. NumPy, first released in 2006, provides fast arrays and maths. pandas, created by Wes McKinney in 2008, adds labelled tables called DataFrames. Matplotlib and seaborn draw charts. scikit-learn, started in 2007, offers classic machine-learning models with one consistent interface. TensorFlow, released by Google in 2015, and PyTorch, released by Meta in 2016, power deep learning. The Hugging Face transformers library gives access to thousands of pre-trained language and vision models. The next modules teach these one by one.

Your own modules

Any .py file is a module. If you save helper functions in utils.py, another file in the same folder can write from utils import calculate_average. A common pattern at the bottom of a module is if __name__ == "__main__":, which runs test or demo lines only when the file is run directly, not when it is imported. Splitting a growing program into modules keeps each file focused and makes the code easier to test and reuse.

  • Never name your own file after a library, such as random.py or numpy.py; Python will import your file instead and strange errors follow.
  • Use help(math) or dir(math) to explore what a module offers.
  • Install third-party packages only from trusted sources; package names can be imitated by attackers.

How it works

ModuleUseful forExample
mathSquare roots, powers, pi, roundingmath.sqrt(81)
randomRandom choices and numbersrandom.choice(names)
datetimeDates and timesdate(2026, 1, 26)
statisticsMean, median, modestatistics.median(xs)
collectionsCounter, deque and moreCounter(words)

In code

Four standard modules in action. The seed makes the random rolls the same every time.

modules.py
import math
import random
from datetime import date
from statistics import mean, median

print("Square root of 81:", math.sqrt(81))
print("Pi to 3 places:", round(math.pi, 3))

random.seed(42)
rolls = [random.randint(1, 6) for _ in range(5)]
print("Five dice rolls:", rolls)

day = date(2026, 1, 26)
print(day, "is a", day.strftime("%A"))

scores = [72, 91, 64, 85, 78]
print("Mean:", mean(scores), "Median:", median(scores))

Output

Square root of 81: 9.0
Pi to 3 places: 3.142
Five dice rolls: [6, 1, 1, 6, 3]
2026-01-26 is a Monday
Mean: 78 Median: 78

Try it yourself

Which module would you import?

Match each task to the standard module that helps.

  • Find the square root of 50
  • Pick a random winner from a list
  • Work out how many days until a festival
  • Find the median of some marks
  • Count how often each word appears

Common mistakes

  • Naming your own file math.py or random.py, which hides the real module.
  • Forgetting the module name: sqrt(16) fails after import math; use math.sqrt(16).
  • Installing packages inside a program. Run pip in the terminal, once.

Check yourself

Question 1

1. After import math, how do you get the square root of 9?

Question 2

2. What does random.seed(42) do?

Question 3

3. How is a third-party package installed?

Summary

  • Modules are reusable Python files; packages group modules.
  • The standard library is built in; pip installs others.
  • import, from … import and import … as are the three forms.

Finished reading?

Sources: Python Standard Library