Skip to content

Python Math, Random Sampling, and Platform Tools

Step 5 of 41

Python Random Sampling, Seeds, and Platform Inspection

Introduction

Python random sampling can select a quiz or allocate a training group. Platform inspection can record which interpreter and operating system generated the result. Together, those tools help make a diagnostic report reproducible and explain differences between environments.

This PCAP-31-03 lesson covers random in objective 1.3 and platform in objective 1.4, within Modules and Packages (12% of the score, 6 of 40 items). You will select without replacement, repeat a sequence under controlled conditions, and interpret platform information.

Learning objectives

After this lesson you can:

  1. Use random.random(), random.randint(), random.choice() and random.sample() and state their return types.
  2. Explain what random.seed() does and what reproducibility does and does not guarantee.
  3. Identify the arguments that make choice() and sample() raise exceptions.
  4. Distinguish sampling without replacement (sample) from repeated independent choices (choice).
  5. Use the platform functions to report the operating system, hardware and Python version.
  6. Recognize that python_version_tuple() returns strings and that results depend on the machine.

The random module

The default generator in random uses deterministic pseudo-random state. Seeding initializes that state. Repeating the seed and the same sequence of calls in a controlled runtime can reproduce the output. The seed is an input to initialization, rather than the entire evolving state.

The main functions

Python
import random

print(random.random())          # a float x with 0.0 <= x < 1.0
print(random.randint(1, 6))     # an int n with 1 <= n <= 6, both ends included
print(random.choice(["red", "green", "blue"]))   # one element of a sequence
print(random.sample(range(1, 50), 6))            # a list of 6 different elements
Function Returns Notes
random.random() float in [0.0, 1.0) 0.0 can occur, 1.0 cannot
random.randint(a, b) int in [a, b] both limits can occur; a must be <= b
random.randrange(stop) / randrange(start, stop) int the stop value is excluded, like range
random.choice(seq) one element the sequence must not be empty
random.sample(population, k) list of k elements no element is picked twice (by position)

The off-by-one rule for randint is a favourite trap: random.randint(1, 6) can return 6, whereas random.randrange(1, 6) can only return 1 to 5.

choice(): one element, may repeat over several calls

random.choice(sequence) picks one element. Calling it several times is a series of independent draws, so the same element can appear again:

Python
import random

colours = ["red", "green", "blue"]
picks = [random.choice(colours) for _ in range(5)]
print(picks)    # for example ['blue', 'blue', 'red', 'green', 'blue']

Passing an empty sequence raises IndexError ("Cannot choose from an empty sequence"):

Python
random.choice([])    # IndexError

sample(): selecting positions without replacement

random.sample(population, k) returns a new list by selecting k distinct positions. The input is unchanged. If the input contains equal values at different positions, the output can contain equal values too.

Python
import random

team = ["Ana", "Ben", "Chloe", "Dev", "Eli"]
winners = random.sample(team, 2)
print(winners)   # for example ['Chloe', 'Ana']
print(team)      # unchanged: ['Ana', 'Ben', 'Chloe', 'Dev', 'Eli']

Three error situations should be on your radar:

Python
random.sample(team, 6)       # ValueError: Sample larger than population or is negative
random.sample(team, -1)      # ValueError: same message
random.sample({1, 2, 3}, 2)  # TypeError: Population must be a sequence
  • k larger than the population size is impossible without replacement, so ValueError.
  • A negative k is also a ValueError.
  • Since Python 3.11, the population must be a sequence. Convert a set to a sequence first, using sorted(s) if its elements are orderable. Earlier versions could accept sets.

Choosing between choice and sample

Question Tool
"Pick one winner" choice
"Pick 3 different winners" sample(population, 3)
"Roll a die 3 times" (repeats are allowed) three calls to randint(1, 6) or choice
"Shuffle the whole list" random.shuffle(list) (changes the list in place) or sample(list, len(list))

Seeds and reproducibility

random.seed(value) sets the internal state of the generator. After a given seed, the following calls always produce the same sequence within the same Python runtime.

Python
import random

random.seed(2024)
first = [random.randint(1, 100) for _ in range(3)]

random.seed(2024)
second = [random.randint(1, 100) for _ in range(3)]

print(first == second)    # True

The comparison prints True, no matter which numbers the lists contain. This is exactly what makes seeds useful:

  • Tests: a test that uses random input can be rerun with the same data when it fails.
  • Demonstrations: a tutorial or a bug report can show identical results.
  • Simulations: you can compare two strategies on identical random draws.

Important limits to remember:

  1. Most algorithms may change across versions. Python documents a compatibility guarantee for random() when a compatible seeder receives the same seed. It does not extend that guarantee to every helper, such as sample(). Record selected IDs when an allocation must survive an upgrade.
  2. When no explicit seed is supplied, initialization uses operating-system randomness when available, or time. Different runs are expected to vary, but identical output remains possible.
  3. The seed does not make the data "more random". It does the opposite: it makes the sequence repeatable. Do not use random for passwords or security tokens; the secrets module exists for that. (This is outside the exam, but it is a useful professional rule.)
  4. State and call order matter. Additional draws or calls from other code can change later results. Use a separate random.Random(seed) instance when other code shares the module-level generator.

Worked example: a reproducible training-group allocator

Problem. A trainer must split 6 participants into a group A of 3 and a group B of 3. She wants a fair random split, but she also needs to regenerate exactly the same split if a participant asks later. Design the code.

Step 1: choose the primitive. The two groups must not overlap, so each participant appears once. random.sample selects three positions for group A. In this example the participant names are unique, so excluding those names gives the other three participants.

Step 2: make it reproducible. Create a dedicated generator from a recorded value, such as the course date. Keep participant IDs and their order stable. See how Python discovers modules if an unexpected local random.py is being imported.

Step 3: code.

Python
import random

participants = ["Ana", "Ben", "Chloe", "Dev", "Eli", "Farah"]

def allocate(seed):
    rng = random.Random(seed)
    group_a = rng.sample(participants, 3)
    group_b = [name for name in participants if name not in group_a]
    return group_a, group_b

run1 = allocate(20261019)
run2 = allocate(20261019)
print(run1 == run2)        # True
print(len(run1[0]), len(run1[1]))   # 3 3

Step 4: explain the result. True is certain: the same seed gives the same sequence, so sample makes the same choice. Lengths are 3 3 because sample returns exactly k items and the remaining three names go to group B. The names in each group are not stated: they depend on the Python runtime.

Why other designs are weaker.

  • Three calls to random.choice(participants) could return the same person twice, so a participant could be in group A twice and another be forgotten.
  • Calling random.sample(participants, 4) for group A would make groups of unequal size, and group B would have only 2 members.
  • Omitting the seed makes regeneration unreliable unless the program stores the chosen IDs or generator state.
  • Putting random.seed(seed) outside the function and calling it only once would make the second call continue the sequence, so run1 == run2 would normally be False. Recreate the initial generator state before each sequence you want to repeat.

The platform module

The platform module reports information about the underlying system. Most functions return strings, and the values depend entirely on the machine where the code runs. This is why exam questions focus on which function answers which question and on types, not on specific output.

Python
import platform

print(platform.platform())              # e.g. 'Linux-6.1.0-x86_64-with-glibc2.36'
print(platform.system())                # e.g. 'Linux', 'Windows' or 'Darwin'
print(platform.machine())               # e.g. 'x86_64' or 'arm64'
print(platform.processor())             # e.g. 'x86_64', or '' on some systems
print(platform.version())               # the operating system release information
print(platform.python_implementation()) # e.g. 'CPython'
print(platform.python_version_tuple())  # e.g. ('3', '11', '4')

What each function reports

Function Answers the question Typical value
platform() One summary string of the platform 'Windows-10-10.0.19045-SP0'
system() Which operating system? 'Linux', 'Windows', 'Darwin'
machine() Which hardware architecture? 'x86_64', 'AMD64', 'arm64'
processor() Which processor? processor name, or an empty string '' when unknown
version() Which OS version/build text? long, system-specific string
python_implementation() Which Python interpreter? 'CPython', 'PyPy', ...
python_version_tuple() Which Python version, as parts? ('3', '11', '4')

Details that the exam likes:

  • platform.platform() accepts the optional arguments aliased and terse. With terse=True it returns a shorter string (only the most important parts). Both default to false.
  • python_version_tuple() returns a tuple of three strings, not integers. platform.python_version_tuple()[0] is '3', so comparing it to 3 is False. Convert with int() before comparing.
  • platform.python_version() (not in the objective list, but related) returns the same information as one string such as '3.11.4'.
  • processor() can be an empty string, since not every system reports it. machine() is more dependable.
  • system() returns '' only if the system cannot be determined; otherwise it gives the short OS name. On macOS the value is 'Darwin', not 'macOS'.
  • Calling platform functions does not require any installation; the module is in the standard library, and there is no platform.cpu_count().

Worked example: a diagnostic environment report

Problem. The support team asks for a short function that prints the platform in a stable layout, and a check that refuses to run on Python older than 3.9. Write it and explain a common bug.

Step 1: collect the values. Use system(), machine(), python_implementation() and python_version_tuple().

Step 2: convert the version parts. The tuple elements are strings, so convert them with int before comparing.

Step 3: code.

Python
import platform

def report():
    major, minor, patch = platform.python_version_tuple()
    lines = [
        f"OS: {platform.system()}",
        f"Machine: {platform.machine()}",
        f"Python: {platform.python_implementation()} {major}.{minor}.{patch}",
    ]
    return "\n".join(lines), (int(major), int(minor))

text, version = report()
print(text)
if version < (3, 9):
    raise SystemExit("Python 3.9 or newer is required")

Step 4: read the result. On a Linux x86-64 server with CPython 3.11 the printed text is three lines: OS: Linux, Machine: x86_64, Python: CPython 3.11.x. The version check compares two tuples of integers, and Python compares tuples element by element, so (3, 11) < (3, 9) is False and the program continues.

The common bug. Writing if platform.python_version_tuple()[1] < 9: compares the string '11' with the integer 9, which raises TypeError. If someone writes < '9' instead, it compares strings, and '11' < '9' is True because the character '1' sorts before '9', so Python 3.11 would wrongly be rejected. Both mistakes come from forgetting that the tuple holds strings.

Common pitfalls and exam tips

  • Exam tip: randint(a, b) includes b; randrange(a, b) does not.
  • Exam tip: random() takes no argument and returns a float below 1.0.
  • Pitfall: Believing random.sample(seq, k) can return more than len(seq) items. It raises ValueError.
  • Pitfall: Expecting random.choice of an empty list to return None. It raises IndexError.
  • Pitfall: Assuming every helper has stable output across Python versions. Check the documented guarantee for random() separately from sample() and other helpers.
  • Pitfall: Reseeding once and expecting two later blocks of draws to match. The sequence continues from where it stopped.
  • Exam tip: All parts of python_version_tuple() are strings.
  • Pitfall: Writing code that depends on an exact platform.version() text or on processor() being non-empty.
  • Exam tip: When asked "which function tells you the operating system name", the answer is platform.system(); for the CPU architecture, platform.machine().

Mini case study: a quiz generator that fails on one laptop

A training company builds a quiz tool that selects 5 questions out of a bank, repeatably per exam session, and prints the environment in the support log.

Python
import random
import platform

bank = [f"Q{n}" for n in range(1, 21)]

def make_quiz(session_id):
    random.seed(session_id)
    return random.sample(bank, 5)

def log_line():
    parts = platform.python_version_tuple()
    return platform.system() + " " + parts[0] + "." + parts[1]

print(make_quiz(7) == make_quiz(7))
print(len(make_quiz(7)))
print(log_line())

A colleague reports two problems: on a machine with a small bank of only 4 questions the tool crashes, and the log line from a Windows laptop shows Windows 3.11, which a script then compares with the number 3.11 and fails.

Questions. What do the three prints show on a normal machine? Why does the small-bank machine crash? What is wrong with the comparison?

Solution.

  1. make_quiz(7) == make_quiz(7) prints True, because the generator is reseeded with the same value before each draw. len(make_quiz(7)) prints 5. The third line prints something like Linux 3.11 or Windows 3.11, because system() and the first two version parts are strings joined with dots.
  2. With a bank of 4 questions, random.sample(bank, 5) asks for more elements than exist, so it raises ValueError: Sample larger than population or is negative. If the requirement is exactly five questions, validate the bank and report a clear error when it is too small. See choosing an exception handler. Using min(5, len(bank)) would implement a different rule that permits shorter quizzes.
  3. The log line is a string such as "Windows 3.11"; comparing it with the float 3.11 never makes sense (equality gives False; ordering with < raises TypeError). Store the version as integers, for example (int(parts[0]), int(parts[1])), and compare tuples.

Side lesson: the quiz is reproducible per session_id within one runtime. If the company upgrades Python, the generated sets could change; if exact repeatability across upgrades is a requirement, store the chosen question IDs instead of regenerating them.

Key terms

  • Pseudo-random generator: an algorithm producing a repeatable-looking random sequence from a seed.
  • Seed: input used to initialize pseudo-random generator state.
  • Sampling without replacement: selecting positions without choosing the same position twice.
  • Population: the sequence from which sample or choice selects.
  • Reproducibility: obtaining the same results again by repeating the same procedure and seed in the same runtime.
  • platform module: standard-library module describing the OS, hardware and Python implementation.
  • Implementation: the interpreter flavour reported by python_implementation(), such as CPython.
  • Version tuple: three strings (major, minor, patch).

Summary checklist

  • I can state the return type and range of random(), randint(), choice() and sample().
  • I know which invalid arguments raise IndexError, ValueError and TypeError.
  • I can explain what seed() guarantees and what it does not.
  • I can choose between choice, sample and repeated draws for a requirement.
  • I can name the platform function that answers each environment question.
  • I know that python_version_tuple() contains strings and that results vary by machine.
  • I can build a short diagnostic report without hard-coding machine-specific values.

Official sources