Random Numbers in Python

Here’s the translation of the Go code to Python, formatted in Markdown suitable for Hugo:

Python’s random module provides pseudorandom number generation.

import random

def main():
    # For example, random.randint returns a random integer n,
    # where a <= n <= b (inclusive).
    print(f"{random.randint(0, 99)},{random.randint(0, 99)}")

    # random.random() returns a random float f,
    # where 0.0 <= f < 1.0.
    print(random.random())

    # This can be used to generate random floats in
    # other ranges, for example 5.0 <= f' < 10.0.
    print(f"{random.uniform(5, 10)},{random.uniform(5, 10)}")

    # If you want a known seed, create a new Random instance
    # with a fixed seed.
    r2 = random.Random(42)
    print(f"{r2.randint(0, 99)},{r2.randint(0, 99)}")

    # Using the same seed will produce the same random numbers.
    r3 = random.Random(42)
    print(f"{r3.randint(0, 99)},{r3.randint(0, 99)}")

if __name__ == "__main__":
    main()

Some of the generated numbers may be different when you run the sample.

$ python random_numbers.py
68,56
0.8090228139659177
5.840125017402497,6.937056298890035
94,49
94,49

The random module in Python provides various functions for generating random numbers. Here are some key points:

  1. random.randint(a, b) generates a random integer N such that a <= N <= b.
  2. random.random() generates a random float between 0.0 and 1.0.
  3. random.uniform(a, b) generates a random float N such that a <= N <= b.
  4. You can create a separate random number generator with a fixed seed using random.Random(seed).

For cryptographically secure random numbers, you should use the secrets module instead.

See the Python random module documentation for references on other random quantities that Python can provide.