On this page

Random & Secrets

Enrico Hochkoeppler Profile

By Enrico Hochkoeppler

Web Developer & TutoriaLibre Founder

Why randomness matters​

Randomness appears in many programs: simulations, games, experiments, A/B testing, password generation, API keys, and session tokens.
The key point: not all randomness is equal.

Python gives you two main tools:

To write correct and safe software, you must understand:


The random module — pseudo‑randomness​

What “pseudo‑random” means​

The random module uses a pseudo‑random number generator (PRNG).
A PRNG:

This is ideal for:

It is not safe for passwords, tokens, or anything involving attackers.


Generating random numbers​

Random float in ([0.0, 1.0))


import random



x = random.random()

This is the base primitive: many other operations are built on top of it.

Random integer (inclusive)


n = random.randint(1, 10)  # 1 ≤ n ≤ 10

Use this when you need a whole number in a closed interval.

Random number from a range with step


n = random.randrange(0, 100, 5)  # 0, 5, 10, ..., 95

This is useful when you need values aligned to a step (e.g., multiples of 5).


Random choice and sampling​

Choose one element from a sequence


item = random.choice(["red", "blue", "green"])

This is like drawing one card from a deck.

Choose multiple elements with replacement


items = random.choices([1, 2, 3], k=5)

Elements can repeat, because each draw is independent.

Choose multiple elements without replacement


subset = random.sample(range(100), 10)

This is like drawing 10 unique lottery numbers from 0–99.

Sampling is fundamental in statistics, testing, and randomized algorithms.


Shuffling sequences​


cards = [1, 2, 3, 4, 5]

random.shuffle(cards)

This randomly reorders the list in place.

Typical uses:


Seeding the random generator​

A PRNG is deterministic: the same seed → the same sequence.


random.seed(42)



print(random.random())

print(random.random())

print(random.random())

If you run this code again with the same seed, you will get the exact same three values.

This is extremely useful for:

But it also shows why random is not secure:
if someone can guess or control the seed, they can predict all “random” values.


The secrets module — cryptographically secure randomness​

Why secrets exists​

Security requires unpredictability.
Attackers must not be able to guess:

The secrets module uses system‑level entropy sources, which are:

You should treat secrets as your default choice for anything involving security.


Secure random numbers​


import secrets



n = secrets.randbelow(100)  # 0 ≤ n < 100

This is the secure counterpart of random.randrange(100).

Use it when you need a random integer that an attacker must not be able to predict.


Secure random choice​


token = secrets.choice(["A", "B", "C"])

This is useful when building secure tokens from a set of characters, such as:


Generating secure tokens​

Hexadecimal token


secrets.token_hex(16)  # 32 hex characters

This returns a random sequence of bytes, encoded as hexadecimal.
Good for logs, IDs, or any place where hex is convenient.

URL‑safe token


secrets.token_urlsafe(32)

This returns a random string safe to use in URLs and cookies.
Typical uses:

These tokens are long and unpredictable, which makes brute‑forcing them impractical.


Comparing random and secrets​

Conceptual comparison​

Featurerandom``secretsMain purposeSimulations, games, samplingSecurity, authenticationPredictable if seed knownYesNo (designed to be unpredictable)Cryptographically secureNoYesUse for passwords/tokensNeverAlways

A simple rule:

If an attacker could benefit from predicting your random values,
use secrets, not random.


Best practices​

These practices reduce the risk of predictable randomness and security vulnerabilities.


Summary​

In this lesson, you learned:

Found this helpful? Share the knowledge...

... or support this project to keep it alive!

Buy Me a Coffee

Previous

Datetime & Time

Next

Itertools & Functools