English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python Basic Tutorial

Python Flow Control

Python Functions

Python Data Types

Python File Operations

Python Objects and Classes

Python Date and Time

Advanced Knowledge of Python

Python Reference Manual

Python Random Module (Random)

You can use the random module to generate random numbers in Python.

Python provides a module called random that can generate random numbers.

These are pseudo-random numbers because the generated number sequence depends on the seed.

If the seed value is the same, the sequence will be the same. For example, if using2As the seed value, the following sequence will always be seen.

import random
random.seed(2)
print(random.random())
print(random.random())
print(random.random())

The output will always follow the following order:

0.9560342718892494
0.9478274870593494
0.05655136772680869

Not so casual?Since this generator is completely deterministic, it must not be used for encryption purposes.

This is a list of functions defined in the random module, and a brief explanation of their functions.

List of functions in the Python random module
FunctionDescription
seed(a=None, version=2)Initialize the random number generator
getstate()Return an object capturing the current internal state of the generator
setstate(state)Restore the internal state of the generator
getrandbits(k)Return a Python integer with k random bits
randrange(start, stop[, step])Return a random integer within the range
randint(a, b)Return a random integer between a and b
choice(seq)Return a random element from a non-empty sequence
shuffle(seq)Random sequence
sample(population, k)Return a list of unique elements from the filled sequence with length ak
random()Return a range of [0.0,1The next random floating-point number of the form .0)
uniform(a, b)Return a random floating-point number between a and b
triangular(low, high, mode)Return a random floating-point number between the lower and upper bounds, and specify the pattern within these boundaries
betavariate(alpha, beta)Beta distribution
expovariate(lambd)Exponential distribution
gammavariate(alpha, beta)Gamma distribution
gauss(mu, sigma)Gaussian distribution
lognormvariate(mu, sigma)Lognormal distribution
normalvariate(mu, sigma)Normal distribution
vonmisesvariate(mu, kappa)

Vonmises distribution

paretovariate(alpha)Pareto distribution
weibullvariate(alpha, beta)Weibull distribution