Sub topic 2
Integer Math, Randomness, and Time
Assume you know variables, functions, control flow, lists, and strings. This chapter uses Python’s standard library, which is included with Python.
Integer math
The math module provides functions for exact integer problems:
factorial(n)returnsn!.comb(n, k)counts unordered selections.perm(n, k)counts ordered selections.gcd(a, b)returns the greatest common divisor.isqrt(n)returns the integer square root, rounded down.
import math
print(math.factorial(5)) # 120
print(math.comb(5, 2)) # 10
print(math.perm(5, 2)) # 20
print(math.gcd(12, 18)) # 6
print(math.isqrt(17)) # 4Generating and selecting random values
The random module generates pseudorandom values. They appear random, but a deterministic algorithm produces them.
Use random() for a float from 0 up to 1, randint(a, b) for an inclusive integer range, and uniform(a, b) for a float range. For sequences, choice selects one item, sample selects distinct items, choices allows repeated selections, and shuffle changes a list in place.
import random
items = ["red", "green", "blue", "yellow"]
print(random.randint(1, 6))
print(random.choice(items))
print(random.sample(items, k=2))
print(random.choices(items, k=3))
random.shuffle(items)
print(items)A seed makes a pseudorandom sequence repeatable. A separate Random instance avoids changing the module-wide generator.
first = random.Random(7)
second = random.Random(7)
print([first.randint(1, 6) for _ in range(3)])
print([second.randint(1, 6) for _ in range(3)])Both lists match, which helps test random code.
Dates, times, and durations
date stores a calendar date. time stores a time of day. datetime combines both. timedelta stores a duration.
from datetime import date, time, datetime, timedelta
day = date(2026, 11, 26)
clock = time(14, 30)
moment = datetime.combine(day, clock)
print(moment)
print(moment + timedelta(hours=2))
print(day + timedelta(days=7))Keep these types distinct. A timedelta represents elapsed time, while a datetime represents a point on a calendar.
Exercise
Which function counts ordered selections of two items from five?
Show answer
math.perm(5, 2).