Python Tutorial (43) - random module

Time: Column:Python views:184

The Python random module is primarily used to generate random numbers. It implements various distributions for pseudorandom number generators.

To use the random module, you must first import it:

import random

View the contents of the random module:

Example:

>>> import random
>>> dir(random)
['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random', 'SG_MAGICCONST', 'SystemRandom', 'TWOPI', '_Sequence', '_Set', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_accumulate', '_acos', '_bisect', '_ceil', '_cos', '_e', '_exp', '_floor', '_inst', '_log', '_os', '_pi', '_random', '_repeat', '_sha512', '_sin', '_sqrt', '_test', '_test_generator', '_urandom', '_warn', 'betavariate', 'choice', 'choices', 'expovariate', 'gammavariate', 'gauss', 'getrandbits', 'getstate', 'lognormvariate', 'normalvariate', 'paretovariate', 'randbytes', 'randint', 'random', 'randrange', 'sample', 'seed', 'setstate', 'shuffle', 'triangular', 'uniform', 'vonmisesvariate', 'weibullvariate']

Generating a random number using the random() method:

The random() method returns a random floating-point number in the half-open interval [0,1), meaning it includes 0 but excludes 1.

Example:

# Import the random module
import random

# Generate a random number
print(random.random())

The output of the above example could be:

0.4784904215869241

The seed() method:

The seed() method changes the seed of the random number generator. You can call this method before using other functions from the random module.

Example:

#!/usr/bin/python3
import random

random.seed()
print("Random number with default seed:", random.random())
print("Random number with default seed:", random.random())

random.seed(10)
print("Random number with seed 10:", random.random())
random.seed(10)
print("Random number with seed 10 again:", random.random())

random.seed("hello", 2)
print("Random number with string seed:", random.random())

The output will be:

Random number with default seed: 0.7908102856355441
Random number with default seed: 0.81038961519195
Random number with seed 10: 0.5714025946899135
Random number with seed 10 again: 0.5714025946899135
Random number with string seed: 0.3537754404730722

random Module Methods

The random module provides the following methods:

MethodDescription
seed()Initializes the random number generator.
getstate()Returns an object capturing the current internal state of the generator.
setstate()Restores the generator's internal state to what was captured by getstate().
getrandbits(k)Returns a Python integer with k random bits.
randrange()Returns a randomly selected element from range(start, stop, step).
randint(a, b)Returns a random integer N such that a <= N <= b.
choice(seq)Returns a random element from a non-empty sequence seq. Raises IndexError if seq is empty.
choices(population, ...)Returns a list of k elements selected from the population.
shuffle(x[, random])Shuffles the sequence x in place.
sample(population, k, ...)Returns a list of k unique elements randomly chosen from the population.
random()Returns a random floating-point number in the range [0.0, 1.0).
uniform(a, b)Returns a random floating-point number N such that a <= N <= b.
triangular(low, ...)Returns a random floating-point number N between low and high with the specified mode.
betavariate(alpha, beta)Beta distribution. The range of returned values is between 0 and 1.
expovariate(lambd)Exponential distribution. The parameter lambd is 1.0 / desired_mean.
gammavariate(alpha, beta)Gamma distribution (not to be confused with the Gamma function). Parameters must satisfy alpha > 0 and beta > 0.
gauss(mu, sigma)Gaussian (Normal) distribution. mu is the mean and sigma is the standard deviation.
lognormvariate(mu, sigma)Log-normal distribution.
normalvariate(mu, sigma)Normal distribution.
vonmisesvariate(mu, kappa)von Mises distribution.
paretovariate(alpha)Pareto distribution.
weibullvariate(alpha, beta)Weibull distribution.

These methods provide a wide range of random number generation capabilities, making the random module versatile for various applications.