CodeBlanks Logo Icon CodeBlanks

Standard library

Learn standard modules like math, random, datetime.

The standard library

The collection of modules that ships with Python is called the standard library. It requires no installation; you use it with import right away:

import math       # sqrt, pi, log
import random     # randint, choice
import datetime   # date, timedelta
import statistics # mean, median

These modules are maintained by the Python community and work on all platforms. Their functions are tested and documented.

They handle many tasks without installing third-party packages.

Common modules

Some modules in the standard library are used often in daily work. math for mathematical functions, random for randomness, datetime for dates and times, statistics for statistics:

import statistics
print(statistics.mean([1, 2, 3, 4]))
# 2.5

import datetime
print(datetime.date.today())
# 2025-01-15

These modules are reliable and fast in their domains. It is wise to check the standard library before turning to third-party packages.

Practice Mean with statistics.mean

Write import statistics. Then write print(statistics.mean([1, 2, 3, 4])).

Starter code

main.py
# load the statistics module
# print the mean of the list

Sample solution

main.py
import statistics
print(statistics.mean([1, 2, 3, 4]))

Expected output

2.5

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the random module

Question
import ____
print(random.randint(1, 6))
Answer
import random
print(random.randint(1, 6))

Explanation: import random generates random numbers.

2 Which is in the standard library?

  • requests
  • numpy
  • pandas
  • math Correct answer

Explanation: math ships with Python; the others are third-party.

3 Match the standard library

Term Meaning
math Square root, pi
random Random number
datetime Date and time
statistics Mean, median

All lessons in Beginner