In Python, the random module provides functions for generating random numbers and selecting random elements from a list.
Here are some examples of using the random module:
import random # Generate a random float between 0 and 1 x = random.random() print(x) # Generate a random float in the range [3, 7) y = random.uniform(3, 7) print(y) # Generate a random integer between 1 and 10 z = random.randint(1, 11) print(z) # Choose a random element from a list my_list = [1, 2, 3, 4, 5] w = random.choice(my_list) print(w) # Shuffle a list random.shuffle(my_list) print(my_list)
You can use the random module to perform various tasks, such as generating random passwords, shuffling a deck of cards, or simulating dice rolls in a game.
Remember that the random numbers generated by the random module are not truly random but are generated using a pseudorandom number generator (PRNG). This means that the numbers are generated using a mathematical algorithm, and while they may appear random, they are determined by a starting value called the seed. If the same seed is used, the same sequence of random numbers will be generated.