Random Module in Python
The `random` module in Python provides functions for generating random numbers. It is part of the standard library and is commonly used in various applications such as simulations, games, and cryptography. Let’s explore the `random` module in detail, including the `range()` function and different ways to generate random numbers.
Basic Random Number Generation:
1. `random()` Function:
– The `random()` function returns a random floating-point number in the range [0.0, 1.0).pythonimport random random_number = random.random() print(random_number)
2. `randrange()` Function:
– The `randrange()` function generates a random integer from the specified range.pythonimport random random_integer = random.randrange(1, 10) # Generates a random integer from 1 to 9 print(random_integer)
Range Functions:
1. `randint()` Function:
– The `randint(a, b)` function returns a random integer in the range [a, b].pythonimport random random_integer = random.randint(1, 10) # Generates a random integer from 1 to 10 print(random_integer)
2. `uniform()` Function:
– The `uniform(a, b)` function returns a random floating-point number in the range [a, b).pythonimport random random_float = random.uniform(1.0, 5.0) # Generates a random float from 1.0 to 5.0 print(random_float)
3. `randint()` vs `randrange()` and `uniform()` vs `random()`:
– `randint(a, b)` is inclusive of both `a` and `b`. – `randrange(a, b)` is exclusive of `b`. – `uniform(a, b)` is used for generating floating-point numbers.Random Sequences:
1. `shuffle()` Function:
– The `shuffle(sequence)` function shuffles a sequence randomly (e.g., a list).pythonimport random my_list = [1, 2, 3, 4, 5] random.shuffle(my_list) print(my_list)
2. `sample()` Function:
– The `sample(sequence, k)` function returns a randomly selected sample of size `k` from a sequence.pythonimport random my_list = [1, 2, 3, 4, 5] random_sample = random.sample(my_list, 3) # Selects 3 random elements from the list print(random_sample)
Seed for Reproducibility:
– Setting a seed using `seed()` ensures reproducibility, meaning the same sequence of random numbers will be generated on different runs.pythonimport random random.seed(42) # Setting a seed random_number = random.random() print(random_number)