Identifiers and randomness

As programs grow beyond one-off scripts, they need ways to distinguish things and to vary their behavior. We often want to label data so it can be tracked reliably, and we sometimes want a program to behave differently each time it runs. Python’s standard library includes simple tools for both of these needs, and they show up quickly in real, stateful programs.

Generating unique identifiers

A common requirement is to create a value that is extremely unlikely to collide with any other value. Python provides this through the uuid module, which can generate universally unique identifiers.

An identifier like this is just data, but it is designed to be safe to use as a label across files, runs, and even machines.

import uuid

page_id = uuid.uuid4()

The value returned can be stored, logged, or written out alongside generated output.

Using identifiers to label data and program state

Once generated, identifiers are usually attached to something meaningful. In a small site generator, we might assign each generated page a stable ID so it can be referenced later.

import uuid

page = {
    "id": str(uuid.uuid4()),
    "title": "Mars",
    "filename": "mars.html"
}

The identifier does not explain the data. It simply gives us a reliable handle we can use in code and stored files.

Generating random numbers

Python also includes the random module, which produces values chosen according to defined rules. These values are not truly random, but they are unpredictable enough for most program behavior.

Random numbers are often used to introduce variation, such as selecting a featured item or choosing between alternatives.

import random

index = random.randint(0, 3)

The program now has a value that can differ each time it runs.

Using randomness to vary program behavior

Random values become useful when they influence decisions. For example, we might randomly select a planet to highlight on a generated homepage.

import random

planets = ["Mercury", "Venus", "Earth", "Mars"]
featured = random.choice(planets)

The program still follows clear rules, but its output can change from run to run without changing the code.

Controlling randomness for repeatable results

Sometimes variation is not what we want. During development or testing, it is often useful to make randomness predictable. This can be done by seeding the random number generator.

import random

random.seed(42)
value = random.randint(1, 10)

With the same seed, the same sequence of “random” values will be produced each time the program runs.

Conclusion

We now have a clear picture of how Python generates unique identifiers and random values, and why both matter in real programs. Identifiers help us label and track data reliably, while randomness allows behavior to vary when we want it to. With these tools, we are oriented and ready to apply them wherever state and variation are needed.