Modules

import math, random, datetime, and json — stdlib only.

import loads a library. This notebook has the Python standard library plus numpy / pandas / matplotlib when imported. Do not pip install.

Goal

Use math, random, datetime, and json — four stdlib modules you will meet constantly.

math

import math

print(math.sqrt(2))
print(math.log(8, 2))
print(math.degrees(math.pi / 2))

random

import random

random.seed(1)
print(random.random())
print(random.randint(1, 6))
print(random.choice(["Nairobi", "Mombasa", "Kisumu"]))
print(random.sample(range(10), 3))

seed makes the sequence repeatable — useful in exercises.

datetime

from datetime import date, datetime, timedelta

today = date(2024, 8, 14)
print(today.isoformat(), today.strftime("%d %b %Y"))
print(today + timedelta(days=7))
print(datetime(2024, 8, 14, 9, 30))

json

import json

row = {"name": "Ada", "score": 98}
text = json.dumps(row)
print(text)
print(json.loads(text)["score"])
print(json.dumps(row, indent=2))

import forms

import math as m
from math import pi, sqrt

print(m.ceil(pi))
print(sqrt(9))

from math import * dumps names into your cell — skip it.

Tip

Need tables? That is pandas — follow Learn pandas after this course. Need a chart? The next-but-one chapter is a first plot.