Apps Productivity How-To

Generate random numbers in Python — integers, floats, secure

Use random for general cases, secrets for security, and the 3.13 CLI.

Use random for general cases, secrets for security, and the 3.13 CLI.

Use the standard library’s random module for simulations and general-purpose randomness, and switch to the secrets module when you need cryptographic strength. The steps below show reliable ways to produce integers, floats, secure values, and command-line outputs.

Method 1: Generate a random integer (general-purpose)

Import the random module.
import random
Create an integer in an inclusive range with random.randint(a, b).
n = random.randint(0, 100)  # 0 ≤ n ≤ 100
print(n)

This produces uniformly distributed integers over the closed interval you specify. For stride/step logic (for example, even numbers only), use random.randrange(start, stop, step).


Method 2: Generate a random float

Import the random module.
import random
Get a float in the half‑open interval [0.0, 1.0) with random.random().
x = random.random()  # 0.0 ≤ x < 1.0
print(x)
Get a float within a range using random.uniform(a, b).
y = random.uniform(2.5, 10.0)  # a ≤ y ≤ b (end inclusion may vary due to floating-point rounding)
print(y)

Use random.random() for quick normalized values, and random.uniform() when you need a specific numeric span.


Method 3: Generate a cryptographically secure random integer

Import the secrets module.
import secrets
Produce a secure integer below a limit with secrets.randbelow(n).
token = secrets.randbelow(10)  # 0..9, suitable for security-sensitive uses
print(token)

Use secrets for passwords, tokens, or any security-related randomness. The random module is deterministic by design and is not suitable for cryptographic purposes.


Method 4: Reproduce results by seeding

Import the random module.
import random
Seed the generator with a fixed value using random.seed(value).
random.seed(42)
Generate values after seeding to get the same sequence across runs (assuming single-threaded use).
print(random.randint(0, 100))
print(random.random())

Seeding stabilizes your outputs for testing and demonstrations. Accepted seed types include None, int, float, str, bytes, and bytearray.


Method 5: Pick random items from a sequence

Import the random module.
import random
Select a single element with random.choice(seq) (sequence must be non-empty).
colors = ["red", "green", "blue"]
print(random.choice(colors))
Draw multiple items with replacement using random.choices(population, k=n).
print(random.choices(colors, k=5))
Draw multiple unique items (no replacement) with random.sample(population, k).
print(random.sample(colors, k=2))

Use weights (via choices(..., weights=[...])) when you need non-uniform probabilities.


Method 6: Use the Python 3.13+ command-line interface

Print a random integer between 1 and N (inclusive).
python -m random 10
# or
python -m random --integer 10
Print a random float between 0 and N (inclusive of 0, end inclusion depends on floating-point rounding).
python -m random --float 1.8
Print a random choice from provided arguments.
python -m random --choice egg bacon sausage spam

This built-in CLI streamlines quick draws without writing a script and is available starting in Python 3.13.


Method 7 (optional): Generate many random numbers efficiently (NumPy)

Import NumPy if you’re working with large arrays or vectorized code.
import numpy as np
Create an array of random integers or floats.
# 15 integers in [0, 10)
ints = np.random.randint(0, 10, size=15)

# 5 floats in [0.0, 1.0)
floats = np.random.random(5)

print(ints)
print(floats)

NumPy’s random routines generate large batches quickly and integrate well with scientific and data workflows.


Tips and cautions

  • For security-sensitive randomness (passwords, tokens), always use secrets, not random.
  • random.random() is half-open: it never returns 1.0.
  • random.uniform(a, b) computes via floating-point arithmetic—due to rounding, the endpoint b may or may not appear.
  • Seed the generator with random.seed() to make tests reproducible.

With these approaches, you can generate integers, floats, reproducible sequences, secure tokens, and even command-line outputs efficiently and correctly.