🎲 Random Numbers

🚀 Open Notebook

Open In Colab Open In Kaggle

📺 Video Tutorial

Watch on YouTube

Generate random numbers in Python 🎲 (9:27)

What You’ll Learn

In this chapter, you’ll master Python’s random module to generate random numbers, make random selections, and shuffle sequences. Random number generation is essential for games, simulations, testing, and adding unpredictability to programs.

Learning Objectives

  • Import and use the random module effectively

  • Generate random integers with randint()

  • Create random floating-point numbers with random()

  • Make random selections from sequences using choice()

  • Shuffle lists in place with shuffle()

  • Apply randomness to practical programming scenarios

Concept Explanation

What is the Random Module?

The random module is a built-in Python library that provides functions for generating pseudo-random numbers. These numbers appear random but are actually generated by a deterministic algorithm that can be reproduced if you know the seed value.

import random

# Now you can use random.randint(), random.choice(), etc.

Why Use Random Numbers?

  1. Games - Dice rolls, card shuffles, enemy behavior

  2. Simulations - Modeling real-world randomness

  3. Testing - Generating random test data

  4. Security - Creating random passwords or tokens (use secrets module for cryptography)

  5. Sampling - Selecting random items from datasets

  6. Variety - Making programs behave differently each time

Key Random Module Functions

1. random.randint(a, b)

Returns a random integer between a and b (both inclusive):

import random

num = random.randint(1, 6)  # Simulates dice roll: 1, 2, 3, 4, 5, or 6
num = random.randint(1, 100)  # Random number from 1 to 100

Note: Both endpoints are inclusive - unlike range(), which is exclusive of the stop value.

2. random.random()

Returns a random floating-point number between 0.0 and 1.0 (1.0 not included):

import random

num = random.random()  # e.g., 0.7854329846
probability = random.random()  # Useful for probability checks

# Scale to different range
num = random.random() * 100  # 0.0 to 100.0

3. random.choice(sequence)

Returns a random element from a non-empty sequence:

import random

colors = ["red", "blue", "green", "yellow"]
color = random.choice(colors)  # Randomly picks one color

# Works with strings too
letter = random.choice("ABCDEFGHIJKLMNOPQRSTUVWXYZ")

4. random.shuffle(sequence)

Shuffles a list in place (modifies the original list):

import random

cards = ["A", "K", "Q", "J", "10"]
random.shuffle(cards)
print(cards)  # Cards now in random order

Important: shuffle() modifies the list in place and returns None!

Understanding Pseudo-Random

Python’s random numbers are pseudo-random - they use a mathematical algorithm:

import random

# Set the seed for reproducible results
random.seed(42)
print(random.randint(1, 10))  # Always same result with seed 42

random.seed(42)  # Reset seed
print(random.randint(1, 10))  # Same result again

For true randomness in cryptographic applications, use the secrets module instead.

Common Patterns

Random Range with Specific Step

# Random even number between 0 and 100
num = random.choice(range(0, 101, 2))

Weighted Random Choice

# More likely to pick "common" than "rare"
items = ["common"] * 7 + ["uncommon"] * 2 + ["rare"] * 1
item = random.choice(items)

Random Boolean

# 50/50 chance
is_heads = random.choice([True, False])
# or
is_heads = random.random() < 0.5

Examples

Example 1: Basic Random Integer

import random

# Simulate dice roll
dice = random.randint(1, 6)
print(f"You rolled: {dice}")

# Random number for game
enemy_health = random.randint(50, 100)
print(f"Enemy has {enemy_health} health")

# Lottery number
lottery = random.randint(1, 100)
print(f"Winning number: {lottery}")

Example 2: Random Float for Probabilities

import random

# Generate random probability
probability = random.random()
print(f"Probability: {probability:.4f}")

# Simulate 30% chance of rain
if random.random() < 0.3:
    print("It's raining!")
else:
    print("No rain today")

# Random price between $10 and $100
price = 10 + (random.random() * 90)
print(f"Price: ${price:.2f}")

Example 3: Random Choice from List

import random

# Rock Paper Scissors
options = ["rock", "paper", "scissors"]
computer_choice = random.choice(options)
print(f"Computer chose: {computer_choice}")

# Random greeting
greetings = ["Hello!", "Hi there!", "Hey!", "Greetings!"]
print(random.choice(greetings))

# Pick random student
students = ["Alice", "Bob", "Charlie", "Diana"]
selected = random.choice(students)
print(f"{selected}, please answer the question")

Example 4: Shuffling a List

import random

# Shuffle deck of cards
cards = ["2", "3", "4", "5", "6", "7", "8", "9", 
         "10", "J", "Q", "K", "A"]

print("Original:", cards)
random.shuffle(cards)
print("Shuffled:", cards)

# Shuffle again for different order
random.shuffle(cards)
print("Shuffled again:", cards)

# Note: shuffle() returns None, modifies in place
result = random.shuffle(cards)  # result is None!

Example 5: Random Password Generator

import random

# Characters for password
uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
lowercase = "abcdefghijklmnopqrstuvwxyz"
digits = "0123456789"
symbols = "!@#$%^&*"

all_chars = uppercase + lowercase + digits + symbols

# Generate 12-character password
password = ""
for _ in range(12):
    password += random.choice(all_chars)

print(f"Random password: {password}")

# Better version using list comprehension
password = "".join(random.choice(all_chars) for _ in range(12))
print(f"Random password: {password}")

Example 6: Random Quiz Question Selector

import random

questions = [
    "What is 2+2?",
    "What is the capital of France?",
    "What is Python?",
    "Who wrote Romeo and Juliet?",
    "What is the largest ocean?"
]

# Create copy and shuffle
quiz = questions.copy()
random.shuffle(quiz)

print("=== RANDOM QUIZ ===")
for i, question in enumerate(quiz[:3], 1):  # Ask 3 random questions
    print(f"{i}. {question}")

Example 7: Dice Rolling Simulator

import random

def roll_dice(num_dice=1, sides=6):
    """Roll multiple dice and return results"""
    rolls = []
    for _ in range(num_dice):
        rolls.append(random.randint(1, sides))
    return rolls

# Roll 2 six-sided dice
result = roll_dice(2, 6)
print(f"You rolled: {result}")
print(f"Total: {sum(result)}")

# Roll 3 twenty-sided dice (D&D style)
result = roll_dice(3, 20)
print(f"3d20 roll: {result}")
print(f"Total: {sum(result)}")

# Simulate 100 dice rolls and find average
rolls = [random.randint(1, 6) for _ in range(100)]
average = sum(rolls) / len(rolls)
print(f"Average of 100 rolls: {average:.2f}")  # Should be close to 3.5

Practice Exercises

Beginner Level

  1. Random Color: Create a list of 5 colors and print a randomly selected color.

  2. Dice Simulator: Simulate rolling a single six-sided die and display the result.

  3. Coin Flip: Use random to simulate a coin flip (Heads or Tails).

  4. Random Temperature: Generate a random temperature between 32°F and 100°F.

  5. Lucky Number: Generate and display 5 random “lucky numbers” between 1 and 50.

Intermediate Level

  1. Multiple Dice Rolls: Simulate rolling two dice, show both results and their sum.

  2. Card Dealer: Create a deck of 13 cards (2-10, J, Q, K, A), shuffle it, and deal 5 cards.

  3. Random Team Generator: Given a list of 10 names, randomly divide them into 2 teams of 5.

  4. Weather Simulator: Randomly select weather conditions with different probabilities (70% sunny, 20% cloudy, 10% rainy).

  5. Random Walk: Simulate a 1D random walk - start at position 0, randomly move left (-1) or right (+1) for 20 steps, show final position.

Advanced Level

  1. Lottery Generator: Generate 6 unique random numbers between 1-49 (no duplicates).

  2. Monte Carlo Pi Estimation: Use random points to estimate the value of π using the Monte Carlo method.

  3. Random Maze Generator: Create a simple maze using random choices for paths and walls in a 2D grid.

  4. Shuffled Quiz: Load 20 questions, randomly select 10, shuffle them, and present the quiz.

  5. Genetic Algorithm Simulation: Create a simple genetic algorithm using random mutation and selection to solve a problem.

Common Mistakes to Avoid

Mistake 1: Forgetting to Import Random

Wrong:

# No import statement
number = randint(1, 10)  # NameError: name 'randint' is not defined

Correct:

import random

number = random.randint(1, 10)  # Works correctly

Why: Must import the module before using its functions.

Mistake 2: Using shuffle() Return Value

Wrong:

import random

cards = ["A", "K", "Q", "J"]
shuffled = random.shuffle(cards)  # shuffled is None!
print(shuffled)  # None

Correct:

import random

cards = ["A", "K", "Q", "J"]
random.shuffle(cards)  # Modifies cards in place
print(cards)  # Shuffled list

# Or create a copy first
original = ["A", "K", "Q", "J"]
cards = original.copy()
random.shuffle(cards)  # original unchanged, cards shuffled

Why: shuffle() modifies the list in place and returns None.

Mistake 3: Off-by-One with randint()

Wrong:

import random

# Trying to get 1-10 but thinking it's like range()
num = random.randint(1, 10)  # Actually gives 1-10 (10 included)

# If you only want 1-9:
num = random.randint(1, 9)  # Correct for 1-9

Correct:

import random

# randint() is inclusive on both ends
num = random.randint(1, 10)  # Gives 1, 2, 3, ..., 10

# This is different from range(1, 10) which is 1, 2, ..., 9

Why: randint(a, b) includes both a and b, unlike range() which excludes the stop value.

Mistake 4: Not Understanding random.random() Range

Wrong:

import random

# Thinking random() gives 0-10
num = random.random()  # Always 0.0 to 0.999... (never 1.0)

Correct:

import random

# random() always returns 0.0 <= x < 1.0
num = random.random()

# To get 0-10, multiply and cast
num = int(random.random() * 10)  # 0-9

# To get 1-10
num = int(random.random() * 10) + 1  # 1-10

# Better: just use randint()
num = random.randint(1, 10)

Why: random() returns float in [0.0, 1.0) - zero to one, excluding one.

Real-World Applications

1. Game Development

Video games use random number generation for loot drops, enemy spawns, critical hit chances, procedural level generation, and AI decision-making to create varied gameplay experiences.

2. Statistical Simulations

Scientists and researchers use random numbers in Monte Carlo simulations to model complex systems, estimate probabilities, test hypotheses, and analyze risk in fields from physics to finance.

3. Machine Learning

ML algorithms use randomness for weight initialization, data shuffling, random sampling for training/test splits, and stochastic processes in algorithms like Random Forests.

4. A/B Testing

Web companies use random assignment to show different versions of websites to users, enabling data-driven decisions about design and features.

Challenge Projects

1. Slot Machine Simulator

Create a slot machine game with random symbols and payouts.

Requirements:

  • 3 reels with symbols (cherry, lemon, bar, seven)

  • Different payout rates for different combinations

  • Track player balance

  • Calculate win probabilities

  • Display statistics after 100 spins

2. Random Quote Generator

Build a program that displays random inspirational quotes.

Requirements:

  • Store 50+ quotes with authors

  • Display random quote each time

  • Ensure no repeats until all quotes shown

  • Save favorite quotes

  • Daily quote feature with timestamp

3. Card Game (Blackjack)

Implement a simplified blackjack game using random card dealing.

Requirements:

  • Create and shuffle 52-card deck

  • Deal cards to player and dealer

  • Calculate hand values (Aces = 1 or 11)

  • Implement hit/stand logic

  • Track wins/losses

4. Random Art Generator

Create ASCII or character-based art using randomness.

Requirements:

  • Generate random patterns or shapes

  • Use random colors (ANSI codes)

  • Create different art styles (geometric, organic, etc.)

  • Allow saving generated art

  • Parameterize complexity and density

5. Evolutionary Simulation

Simulate evolution using random mutations and selection.

Requirements:

  • Create population of “creatures” with random traits

  • Simulate reproduction with random mutation

  • Apply selection pressure (fittest survive)

  • Track trait changes over generations

  • Visualize evolution over time


🎓 Key Takeaways from Video

  1. Lists store multiple items in a single variable

  2. Import modules to use external code

  3. Use loops to repeat actions

  4. Use if-elif-else for conditional logic

💡 These points cover the main concepts from the video tutorial to help reinforce your learning.