In Python, the `random` module is a built-in module.
The "random" module in Python provides functions for generating random numbers, selecting random elements from sequences, shuffling sequences randomly, and more.
The `random.random()` function returns a float number that ranges from 0.0 to 1.0. There are no parameters required for this function to be invoked.
Common functionalities provided by the "random" module:
It returns a random floating-point number in the range [0.0, 1.0].
# import random module import random # Print random value generate through function print(random.random()) # Output: random value in range[0.0, 1.0]
It returns a random integer in the range [a, b] supplied, including both endpoints.
# import random module import random # Print random value generate through random.randint function print(random.randint(1, 10)) # Output: it will generate random integer number between 1 to 10
It returns a random floating-point number in the range [a, b], or [a, b] if a == b.
# import random module import random print(random.uniform(1.5, 2.5)) # Output: 1.5209130579399674
It returns a random element from the non-empty sequence.
# import random module import random sequence = ['apple', 'banana', 'orange'] print(random.choice(sequence)) # Output: apple
It returns a random value from a specified range using the random.randrange() function. syntax: randrange(start= default set to 0, stop=default set to 1, step=optional); By default, the start is set to 0. Likewise, the step is set to 1 by default.
# Import random module import random range1 = random.randrange(2, 5) print(range1) range2 = random.randrange(2, 20, 4) print(range2)
It returns a list of k elements from the sequence with replacement. The weights parameter allows us to specify the probability of each component.
# Import random module import random sequence = ['apple', 'banana', 'orange'] weights = [0.6, 0.3, 0.1] print(random.choices(sequence, weights=weights, k=2))
Shuffles the elements of the sequence in place.
# Import random module import random # genrate a sequence sequence = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'] # it will shuffle the sequence random.shuffle(sequence) # Print the result print(sequence)
It returns a new list containing k unique elements chosen randomly from the population sequence without replacement.
# import random module import random # generate a dataset population = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] # It will pick 5 items randomly from population list print(random.sample(population, 5))
Initialize the random number generator with a seed value. This allows us to reproduce the same sequence of random numbers.
import random random.seed(42) print(random.random())