The math, random and statistics Modules

50 min read Dictionaries and Python Modules

This is a free course. Log in to run the code exercises and track your progress.

The math, random and statistics Modules

A module is a file of ready-made functions and constants. Load it with import module and use module.name, or import single names with from module import name.

  • math: pi, e, sqrt(), ceil(), floor(), pow(), fabs(), sin(), cos(), tan() (angles in radians).
  • random: random() (a float from 0 up to 1), randint(a, b) (an integer from a to b, both included), randrange(start, stop, step) (like range, stop excluded).
  • statistics: mean(), median(), mode().
import math
from statistics import mean, median, mode
print(math.ceil(4.1), math.floor(4.9))   # 5 4
print(math.sqrt(81), math.fabs(-3))      # 9.0 3.0
data = [4, 8, 6, 8, 9]
print(mean(data), median(data), mode(data))   # 7 8 8

The output of random changes on every run, which makes it good for games and simulations but impossible to compare with a fixed expected answer. random.seed(n) makes the sequence repeat when you need to test it.

Python exercise

Read a radius and print the area and circumference of the circle with two decimals on two lines (Area: ..., Circumference: ...). Use math.pi.

import math
r = float(input())
area = 3.14 * r  # use math.pi and r squared
circumference = 0
print(f"Area: {area:.2f}")
print(f"Circumference: {circumference:.2f}")

Log in to edit and run this code.