Python 3D Academyবাংলা

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 included
  • random.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 n
  • date(year, month, day): a calendar date; subtracting two gives the days between

Step by step, for random.seed(1) then random.randint(1, 6):

  1. The seed sets the recipe's starting point.
  2. randint takes the next number from the recipe and fits it into 1 to 6.
  3. 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"]))
The same seed gives the same rolls. Take out the seed lines to get different ones each run.

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) gives ValueError: day 30 must be in range 1..29 for month 2 in year 2024.

Quiz

  1. What does this print?

    from collections import Counter
    print(Counter("hello")["l"])
  2. 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
  3. What does this print?

    from datetime import date
    print((date(2024, 1, 31) - date(2024, 1, 1)).days)
  4. What does this print?

    from collections import Counter
    print(Counter(["a", "b", "a"]).most_common(1))
  5. Which line has a mistake?

    import random
    
    roll = randint(1, 6)
    print(roll)

Coding tasks

  1. Write most_common_letter(word) that returns the letter that appears most often, using Counter (if there's a tie, the one that appears first).

  2. Write day_of_year(month, day) that returns which day of 2024 that date is (January 1st is day 1), using datetime.date.

  3. Write roll(seed) that sets the random seed to seed, then returns random.randint(1, 6).