The Random Module
What is the Random Module?
The random module provides functions for generating random numbers and making random selections. It’s perfect for games, quizzes, simulations, and shuffling data.
To use it, you must import it first:
import random
This gives you access to all the random functions like random.choice(), random.shuffle(), etc.
← Back to where you were | → Start the course from the beginning
—
Random Numbers
random.randint(a, b) - Random Integer
Returns a random whole number between a and b (inclusive - both ends included).
import random
# Random number from 1 to 6 (like rolling a die)
die_roll = random.randint(1, 6)
print(die_roll) # Could be: 1, 2, 3, 4, 5, or 6
# Random number from 1 to 100
score = random.randint(1, 100)
print(score) # Could be any number from 1 to 100
Use cases:
- Simulating dice rolls
- Random scores
- Random ages
- Any random whole number
random.random() - Random Decimal
Returns a random decimal number between 0.0 and 1.0 (not including 1.0).
import random
num = random.random()
print(num) # e.g., 0.7234891, 0.1829374, 0.9123456
# Scale it up for different ranges
percentage = random.random() * 100 # 0.0 to 100.0
print(f"{percentage:.1f}%") # e.g., 73.2%
random.uniform(a, b) - Random Decimal in Range
Returns a random decimal between a and b.
import random
# Random temperature between 15.0 and 30.0
temperature = random.uniform(15.0, 30.0)
print(f"{temperature:.1f}°C") # e.g., 23.7°C
# Random price between 10.00 and 50.00
price = random.uniform(10.0, 50.0)
print(f"${price:.2f}") # e.g., $34.89
← Back to where you were | → Start the course from the beginning
—
Random Selections
random.choice(sequence) - Pick One Random Item
Picks one random item from a sequence (list, tuple, or string).
import random
# Random color
colors = ["red", "blue", "green", "yellow"]
random_color = random.choice(colors)
print(random_color) # e.g., "blue"
# Random letter
letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
random_letter = random.choice(letters)
print(random_letter) # e.g., "M"
# Random day
days = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")
random_day = random.choice(days)
print(random_day) # e.g., "Thursday"
random.sample(sequence, k) - Pick Multiple Random Items
Picks k random items from a sequence without duplicates.
import random
# Pick 3 random numbers from 1-10 (no repeats)
numbers = list(range(1, 11)) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
winners = random.sample(numbers, 3)
print(winners) # e.g., [7, 2, 9]
# Pick 5 random groups
groups = [
("John", "Mary"),
("Tracy", "Mo", "Sara"),
("Mona", "Kevin", "Abdul"),
("Lina", "Sandra"),
("Issac", "Antony", "Claire"),
("Chloe", "James"),
("Denise", "Kong", "Enzo")
]
selected_groups = random.sample(groups, 5)
# Returns 5 unique groups (no group appears twice)
Key difference from random.choice():
choice()picks one itemsample(k)picks k unique items
← Back to where you were | → Start the course from the beginning
—
Shuffling
random.shuffle(list) - Randomize Order
Shuffles a list in place (changes the original list).
import random
# Shuffle a deck of cards
cards = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]
random.shuffle(cards)
print(cards) # e.g., ['7', 'K', '2', '5', 'A', '9', ...]
# Shuffle flashcards
flashcards = [("Dog", "Hund"), ("Cat", "Katze"), ("House", "Haus")]
random.shuffle(flashcards)
# Now flashcards are in random order
Important: random.shuffle() changes the original list and returns None.
# ❌ Wrong - shuffle returns None!
cards = ["A", "2", "3"]
shuffled = random.shuffle(cards)
print(shuffled) # None!
# ✅ Correct - shuffle modifies the list
cards = ["A", "2", "3"]
random.shuffle(cards)
print(cards) # ['3', 'A', '2']
← Back to where you were | → Start the course from the beginning
—
Sequences vs. Unordered Collections
What Are Sequences?
Sequences are ordered collections where items have positions.
- Lists:
["a", "b", "c"] - Tuples:
("a", "b", "c") - Strings:
"abc" - Ranges:
range(1, 10)
Unordered collections don’t have positions.
- Dictionaries:
{"a": 1, "b": 2} - Sets:
{"a", "b", "c"}
Why This Matters
Many random functions, e.g. shuffle(), choice(), sample() only work with sequences since they need to access items by position (index). Unordered collections such as dictionaries and sets don’t have positions.
import random
# ❌ Doesn't work with dictionaries
flashcards = {"Dog": "Hund", "Cat": "Katze", "House": "Haus"}
random.choice(flashcards) # TypeError: 'dict' object is not subscriptable
# ❌ Doesn't work with sets
colors = {"red", "blue", "green"}
random.choice(colors) # TypeError: 'set' object is not subscriptable
Converting unordered collections to sequences
Solution: Convert to a list first!
Converting Sets
import random
# Convert set to list first
colors = {"red", "blue", "green", "yellow"}
random_color = random.choice(list(colors))
print(random_color) # e.g., "blue"
Converting Dictionaries
import random
flashcards = {"Dog": "Hund", "Cat": "Katze", "House": "Haus"}
# Option 1: Random key
random_key = random.choice(list(flashcards.keys()))
print(random_key) # e.g., "Cat"
# Option 2: Random value
random_value = random.choice(list(flashcards.values()))
print(random_value) # e.g., "Katze"
# Option 3: Random (key, value) pair
random_pair = random.choice(list(flashcards.items()))
english, german = random_pair
print(f"{english} = {german}") # e.g., "Dog = Hund"
Breaking it down:
flashcards = {"Dog": "Hund", "Cat": "Katze"}
# 1. Get dictionary items (not a sequence yet)
items = flashcards.items()
print(type(items)) # <class 'dict_items'>
# 2. Convert to list (now it's a sequence!)
items_list = list(items)
print(type(items_list)) # <class 'list'>
print(items_list) # [('Dog', 'Hund'), ('Cat', 'Katze')]
# 3. Now random.choice() works!
random_card = random.choice(items_list)
print(random_card) # e.g., ('Cat', 'Katze')
← Back to where you were | → Start the course from the beginning
—
Practical Examples
Example 1: Random Flashcard Quiz
import random
flashcards = {
"Dog": "Hund",
"Cat": "Katze",
"House": "Haus",
"Car": "Auto",
"Book": "Buch"
}
# Pick 3 random flashcards to practice
num_questions = 3
flashcard_items = list(flashcards.items())
selected_cards = random.sample(flashcard_items, num_questions)
for english, german in selected_cards:
user_answer = input(f"Translate '{english}': ")
if user_answer.lower() == german.lower():
print("Correct! ✓")
else:
print(f"Wrong! The answer was '{german}'")
Example 2: Shuffle and Practice All Cards
import random
flashcards = [
("Dog", "Hund"),
("Cat", "Katze"),
("House", "Haus")
]
# Practice all cards in random order
random.shuffle(flashcards)
for english, german in flashcards:
user_answer = input(f"Translate '{english}': ")
if user_answer.lower() == german.lower():
print("Correct! ✓")
else:
print(f"Wrong! The answer was '{german}'")
Example 3: Random Number Guessing Game
import random
# Computer picks a random number
secret_number = random.randint(1, 100)
attempts = 0
print("I'm thinking of a number between 1 and 100...")
while True:
guess = int(input("Your guess: "))
attempts += 1
if guess < secret_number:
print("Too low!")
elif guess > secret_number:
print("Too high!")
else:
print(f"Correct! You got it in {attempts} attempts!")
break
Example 4: Random Team Generator
import random
students = ["Alice", "Bob", "Charlie", "Diana", "Eve", "Frank"]
# Shuffle students
random.shuffle(students)
# Split into two teams
team_size = len(students) // 2
team1 = students[:team_size]
team2 = students[team_size:]
print(f"Team 1: {', '.join(team1)}")
print(f"Team 2: {', '.join(team2)}")
← Back to where you were | → Start the course from the beginning
Quick Reference
| Function | What It Does | Needs Sequence? | Example |
|---|---|---|---|
random.randint(a, b) |
Random integer between a and b | No | random.randint(1, 6) |
random.random() |
Random decimal 0.0 to 1.0 | No | random.random() |
random.uniform(a, b) |
Random decimal between a and b | No | random.uniform(10.0, 20.0) |
random.choice(seq) |
Pick one random item | Yes | random.choice([1,2,3]) |
random.sample(seq, k) |
Pick k unique items | Yes | random.sample([1,2,3], 2) |
random.shuffle(list) |
Randomize list order | Yes (list only) | random.shuffle(my_list) |
← Back to where you were | → Start the course from the beginning
Common Mistakes
Mistake 1: Using shuffle() on Dictionaries
# ❌ Wrong - can't shuffle dictionaries
flashcards = {"Dog": "Hund", "Cat": "Katze"}
random.shuffle(flashcards) # TypeError!
# ✅ Correct - convert to list first
flashcard_list = list(flashcards.items())
random.shuffle(flashcard_list)
Mistake 2: Assigning shuffle() Result
# ❌ Wrong - shuffle returns None
cards = ["A", "2", "3"]
shuffled = random.shuffle(cards)
print(shuffled) # None!
# ✅ Correct - shuffle modifies the list
cards = ["A", "2", "3"]
random.shuffle(cards)
print(cards) # ['3', 'A', '2']
Mistake 3: Forgetting to Import
# ❌ Wrong - forgot to import
random.randint(1, 10) # NameError: name 'random' is not defined
# ✅ Correct
import random
random.randint(1, 10)
Mistake 4: Using choice() Without list()
# ❌ Wrong - dict.items() is not a list
flashcards = {"Dog": "Hund"}
random.choice(flashcards.items()) # TypeError!
# ✅ Correct - convert to list
random.choice(list(flashcards.items()))
← Back to where you were | → Start the course from the beginning
Summary
Key points:
- Import first:
import random - Sequences required:
choice(),sample(), andshuffle()only work with sequences (lists, tuples, strings) - Convert dictionaries/sets: Use
list()to convert before using random functionslist(dict.keys())- list of keyslist(dict.values())- list of valueslist(dict.items())- list of (key, value) pairs
- shuffle() modifies in place: Doesn’t return anything
- sample() for unique items: No duplicates in the selection
Most useful for beginners:
random.randint()- Random whole numbersrandom.choice()- Pick one random itemrandom.sample()- Pick multiple unique itemsrandom.shuffle()- Randomize order
← Back to where you were | → Start the course from the beginning
