Handy modules: random, collections, datetime
🌍 In real life. A Ludo game needs a die; a teacher counting votes needs tally marks; anyone planning a trip needs a calendar. These everyday jobs come up in programs all the time, so Python's standard library has a ready tool for each.
The idea in one sentence: random picks by chance, collections.Counter counts things in one line, and datetime.date does calendar maths.
Its words:
random.randint(a, b): a whole number from a to b, both includedrandom.choice(items): one item picked at random- seed: the starting point of the random recipe;
random.seed(1)makes the same numbers every run Counter(items): a dictionary of counts;most_common(n)gives the top ndate(year, month, day): a calendar date; subtracting two gives the days between
Step by step, for random.seed(1) then random.randint(1, 6):
- The seed sets the recipe's starting point.
randinttakes the next number from the recipe and fits it into 1 to 6.- With the same seed, you get the same sequence every time you run it.
import random
random.seed(1)
print([random.randint(1, 6) for _ in range(5)])
random.seed(1)
print([random.randint(1, 6) for _ in range(5)])
print(random.choice(["rock", "paper", "scissors"]))collections.Counter counts things for you, like the counting dictionaries from Chapter 11, in one line. most_common(n) gives the n most common items.
from collections import Counter
counts = Counter("banana")
print(counts)
print(counts["a"], counts["z"])
print(counts.most_common(1))datetime.date holds a calendar date. Subtracting two dates tells you how many days are between them.
from datetime import date
start = date(2024, 1, 1)
trip = date(2024, 3, 1)
print(trip - start)
print((trip - start).days)
print(trip.year, trip.month, trip.day)How "random" works. A computer can't toss a coin, so random uses a recipe that turns one number into the next in a way that looks random. That's why a seed repeats the sequence exactly, which makes programs with randomness testable. (For passwords or anything secret, Python has a separate secrets module.)
Mistakes and edge cases.
- Expecting randint to leave out b. Unlike
range,randint(1, 6)can give 6. - choice of an empty list.
random.choice([])fails with an IndexError. - Counter of a missing item.
counts["z"]is 0, not a KeyError (above). - An impossible date.
date(2024, 2, 30)givesValueError: day 30 must be in range 1..29 for month 2 in year 2024.
Quiz
What does this print?
from collections import Counter print(Counter("hello")["l"])Why call
random.seed(1)before rolling?- To get the same numbers every run
- To make the numbers bigger
- Python needs it, or random won't work
What does this print?
from datetime import date print((date(2024, 1, 31) - date(2024, 1, 1)).days)What does this print?
from collections import Counter print(Counter(["a", "b", "a"]).most_common(1))Which line has a mistake?
import random roll = randint(1, 6) print(roll)
Coding tasks
Write
most_common_letter(word)that returns the letter that appears most often, usingCounter(if there's a tie, the one that appears first).Write
day_of_year(month, day)that returns which day of 2024 that date is (January 1st is day 1), usingdatetime.date.Write
roll(seed)that sets the random seed to seed, then returnsrandom.randint(1, 6).