Skip to main content
Back to module
Python Fundamentals · Files, Modules, and Packages

Modules and the standard library

Reading42mLesson 2 of 3 in this module

Import modules, use math, statistics and datetime from the standard library, and know when to reach for a package.

Why it matters

Python comes with a large standard library: hundreds of modules for maths, statistics, dates, text, files, data formats and more, already installed wherever Python is. Before you write something yourself, it is worth checking whether the standard library already does it, tested and documented. Knowing how import works also prepares you for third-party packages such as pandas or requests, and for splitting your own programs into several files.

Importing a module

A module is a file of Python code with functions and values you can use. Bring one in with import:

import math

print(math.pi)            # 3.141592653589793
print(math.sqrt(16))      # 4.0
print(math.ceil(4.2))     # 5
print(math.floor(4.8))    # 4
print(math.hypot(3, 4))   # 5.0  (length of the hypotenuse)

You use the module's contents with a dot: math.sqrt. This keeps names organised: math.sqrt cannot clash with a sqrt of your own.

Other import forms:

from math import sqrt, pi     # bring specific names in directly
print(sqrt(2) * pi)

import statistics as st       # give a module a shorter alias
print(st.mean([1, 2, 3]))

Avoid from math import *. It dumps every name into your program, so readers cannot tell where a name came from and your own variables can be silently overwritten.

Put imports at the top of the file, one per line. That way anyone reading the file sees immediately what it depends on.

math: numbers and geometry

import math

radius = 2.5
area = math.pi * radius ** 2
print(f"{area:.2f}")                  # 19.63

angle = math.radians(30)              # trig functions use radians
print(round(math.sin(angle), 3))      # 0.5
print(math.isclose(0.1 + 0.2, 0.3))   # True: safe float comparison
print(math.log10(1000))               # 3.0

math.isclose is the right way to compare floats, avoiding the 0.30000000000000004 surprise.

statistics: quick summaries

import statistics

readings = [21.5, 22.0, 23.25, 22.75, 21.0]

print(statistics.mean(readings))             # 22.1
print(statistics.median(readings))           # 22.0
print(round(statistics.stdev(readings), 3))  # 0.912 (sample standard deviation)
print(statistics.mode([3, 1, 3, 2]))         # 3

For small and medium data sets, statistics covers most of what you need without installing anything. (The Statistics Fundamentals course explains what these numbers mean.)

datetime: dates and times

Dates are deceptively tricky: months have different lengths, years have leap days. The datetime module handles that for you:

from datetime import date, datetime, timedelta

start = date(2026, 10, 1)
due = date.fromisoformat("2026-12-25")        # parse "YYYY-MM-DD"
print((due - start).days)                     # 85   (a timedelta, in days)
print(start + timedelta(days=30))             # 2026-10-31
print(start.strftime("%d %b %Y"))             # 01 Oct 2026
print(start.weekday())                        # 3 (Monday is 0, so Thursday)

stamp = datetime.fromisoformat("2026-10-01T14:30:00")
print(stamp.hour, stamp.minute)               # 14 30

Subtracting two dates gives a timedelta; its .days attribute is the gap in whole days. ISO format (2026-10-01) is unambiguous and sorts correctly as text, so it is the best choice for files and logs.

A tour of other useful modules

ModuleUse it for
randomrandom numbers, shuffling, sampling (random.choice, random.randint)
collectionsCounter, defaultdict, namedtuple
itertoolscombinations, permutations, grouping
jsonreading and writing JSON
csvreading and writing CSV
reregular expressions for text patterns
pathlibworking with file paths
fractions, decimalexact fractions and exact decimal money maths

The official documentation at docs.python.org lists them all. Typing help(math) or dir(math) in the interactive shell also shows what a module contains.

Your own modules

Any .py file is a module. If you save functions in units.py, another file in the same folder can use them:

# units.py
def c_to_f(c):
    return c * 9 / 5 + 32
# main.py
import units
print(units.c_to_f(100))    # 212.0

Code at the top level of units.py runs when it is imported. To include test or demo code that runs only when you run the file directly, guard it:

if __name__ == "__main__":
    print(c_to_f(100))

Packages from outside the standard library

Third-party packages (pandas, numpy, requests and thousands more) are published on the Python Package Index (PyPI) and installed with pip install package-name, ideally inside a virtual environment (python3 -m venv .venv) so each project has its own set. Once installed, you import them in exactly the same way. Install only well-known, maintained packages, and check the spelling: look-alike malicious packages do exist. The exercises in this course use only the standard library.

Common mistakes

  • Naming your file after a module. A file called math.py or statistics.py in your folder hides the real module and causes baffling errors.
  • Forgetting the module prefix. After import math, it is math.sqrt, not sqrt.
  • Degrees instead of radians. math.sin(30) is not 0.5. Convert with math.radians.
  • Comparing dates as text in the wrong format. "1/10/2026" style strings do not sort correctly; parse them into date objects.

Quick recap

  • import module then module.name; or from module import name; or import module as alias.
  • math for maths, statistics for summaries, datetime for dates and durations.
  • Check the standard library before writing your own version.
  • Any .py file can be imported; guard demo code with if __name__ == "__main__":.
  • Third-party packages come from PyPI via pip, inside a virtual environment.

Try it

In the Do tab you will use math, statistics and datetime to finish three small helper functions.

Also in this lesson: