Python Random Module
The random
module in Python provides functions that allow you to generate random numbers, select random elements from a list, and perform other randomization tasks. It's widely used in applications like simulations, games, and testing.
Commonly Used Functions
random()
: Returns a random float number between 0.0 and 1.0.randint(a, b)
: Returns a random integer betweena
andb
(both inclusive).choice(seq)
: Returns a random element from a non-empty sequence (like a list or tuple).shuffle(seq)
: Shuffles the elements in a list in place.sample(population, k)
: Returns a list ofk
unique elements chosen from the population.
Example Usage
Python
import random
print(random.random()) # Random float between 0.0 and 1.0
print(random.randint(1, 10)) # Random integer between 1 and 10
print(random.choice(["apple", "banana", "cherry"])) # Random element from list
numbers = [1, 2, 3, 4, 5]
random.shuffle(numbers) # Shuffle list in place
print(numbers)
Import Links
Here are some useful import links for further reading: