To use functions from the random module, you first need to import it:
import random
Quick links:
Random Float (0.0 to 1.0):
random_float = random.random()
# Returns a random floating-point number between 0.0 (inclusive) and 1.0 (exclusive).
Random Integer (inclusive):
random_int = random.randint(a, b)
# Returns a random integer N such that a <= N <= b.
a, b: Integers representing the inclusive range.Random Integer (range with step):
random_range_int = random.randrange(start, stop, step)
# Returns a randomly selected element from range(start, stop, step).
start: The starting number (inclusive).stop: The number to stop before (exclusive).step: The increment between numbers (default is 1).Random Float within a Range:
random_uniform_float = random.uniform(a, b)
# Returns a random floating-point number N such that a <= N <= b or b <= N <= a.
a, b: Numbers representing the range endpoints.Random Choice from a Sequence:
random_element = random.choice(sequence)
# Returns a randomly selected element from a non-empty sequence (list, tuple, string, etc.).
sequence: A non-empty sequence.Shuffle a Sequence (in place):
my_list = [1, 2, 3, 4, 5]
random.shuffle(my_list)
# Shuffles the sequence in place (modifies the original list). Returns None.
sequence: A mutable sequence (like a list).Random Sample (without replacement):
random_sample = random.sample(population, k)
# Returns a new list containing k unique elements chosen from the population sequence or set.
population: A sequence or set to sample from.k: The number of unique elements to choose.