Mastering the Random Module

Python's random module offers various ways to generate randomness. Let's explore its most useful functions for different scenarios.

Essential Random Functions

random.randint()

# Random integer in range [a, b]
dice = random.randint(1, 6)

random.choice()

# Random element from sequence
fruits = ["apple", "banana", "cherry"]
snack = random.choice(fruits)

random.shuffle()

# Shuffle list in place
cards = list(range(52))
random.shuffle(cards)

random.sample()

# Unique random selection
winners = random.sample(players, 3)

Advanced Randomization

random.uniform()

# Random float in range
temperature = random.uniform(35.5, 39.5)

random.choices()

# Weighted selections
colors = ["red", "blue"]
picks = random.choices(colors, weights=[3, 1], k=10)

Practical Use Cases

Game Development

# Random enemy spawn
spawn_points = random.sample(map_locations, 5)
enemy_type = random.choice(["zombie", "skeleton", "orc"])

Data Science

# Train/test split
test_indices = random.sample(range(len(data)), int(len(data)*0.2))

Your Task: Random Operations

Implement various random operations:

  1. Generate random number with randint()
  2. Select random color with choice()
  3. Shuffle a list of numbers
  4. Create lottery numbers with sample()

Note: Check uses fixed mock values for reliable testing

Section 1/4Essential Random Functions

Essential Random Functions

random.randint()

Mastering the Random Module

Python's random module offers various ways to generate randomness. Let's explore its most useful functions for different scenarios.

Essential Random Functions

random.randint()

# Random integer in range [a, b]
dice = random.randint(1, 6)

random.choice()

# Random element from sequence
fruits = ["apple", "banana", "cherry"]
snack = random.choice(fruits)

random.shuffle()

# Shuffle list in place
cards = list(range(52))
random.shuffle(cards)

random.sample()

# Unique random selection
winners = random.sample(players, 3)

Output:

Click "Check" to run your code.