Python Random Module
The random
module in Python provides a set of functions for generating random numbers. These functions can be used to generate random integers, floating-point numbers, and to randomize the order of lists.
Syntax
The random
module has several functions. Some of the commonly used ones are:
import random
random.random()
random.randint(a,b)
random.choice(seq)
random.shuffle(seq)
Example
import random
# Generate a random float between 0 and 1
print(random.random())
# Generate a random integer between 1 and 10
print(random.randint(1, 10))
# Randomly pick an element from a list
my_list = ["apple", "banana", "cherry"]
print(random.choice(my_list))
# Shuffle a list randomly
random.shuffle(my_list)
print(my_list)
Output
0.6356143427728484
5
banana
['banana', 'cherry', 'apple']
Explanation
random.random()
generates a random float between 0 and 1.random.randint(a, b)
generates a random integer betweena
andb
(inclusive).random.choice(seq)
returns a randomly chosen element fromseq
.random.shuffle(seq)
shuffles the elements ofseq
randomly.
Use
The random
module can be used in various applications such as games, simulations, and cryptography. It is also useful for generating test data and randomizing the order of lists.
Important Points
- The
random
module uses a pseudo-random number generator, which means that the numbers generated are not truly random but appear to be so. - The
random
module should not be used for generating secure random numbers, such as for cryptographic applications. For this, you should use thesecrets
module instead. - To generate the same sequence of random numbers repeatedly, you can use the
random.seed()
function.
Summary
The random
module in Python is used to generate random numbers. It provides functions for generating random integers, floating-point numbers, and choosing elements randomly from a list. It is useful for games, simulations, and generating test data, among others. However, it should not be used for generating secure random numbers.