Chapter 4: Random Numbers and Games / Lesson 23

Random Number Generator

Introduction to Random Numbers

Random numbers are essential for creating unpredictable behavior in programs. Python's random module provides functions for generating random numbers, which is perfect for games, simulations, testing, and creating varied experiences.

Understanding how to generate random numbers opens up possibilities for creating interactive programs, games, simulations, and testing scenarios where unpredictability is desired.

Importing the random Module

Before using random functions, you need to import the random module. This is a built-in Python module, so no installation is required.

import_random.py
# Import the random module import random # Now you can use random functions print("Random module imported successfully!")

random.randint() - Random Integers

The random.randint(a, b) function returns a random integer between a and b (inclusive). This is perfect for generating random whole numbers within a specific range.

randint.py
import random # Generate a random integer between 1 and 10 (inclusive) number = random.randint(1, 10) print(number) # Could be 1, 2, 3, ..., or 10 # Generate multiple random numbers for i in range(5): num = random.randint(1, 100) print(num, end=" ") # Common use cases dice_roll = random.randint(1, 6) # Simulate a die age_guess = random.randint(18, 80) # Random age print(f"\nDice roll: {dice_roll}") print(f"Random age: {age_guess}")

random.random() - Random Floats

The random.random() function returns a random float between 0.0 and 1.0 (exclusive of 1.0). This is useful for probability calculations and generating decimal values.

random_float.py
import random # Generate random float between 0.0 and 1.0 value = random.random() print(value) # e.g., 0.73482347 # Generate multiple random floats for i in range(3): print(random.random()) # Scale to different ranges # Random float between 0 and 10 scaled = random.random() * 10 print(f"Random 0-10: {scaled:.2f}") # Random float between 5 and 15 scaled_range = random.random() * 10 + 5 print(f"Random 5-15: {scaled_range:.2f}")

random.uniform() - Random Floats in Range

The random.uniform(a, b) function returns a random float between a and b. It's more convenient than scaling random.random() for specific ranges.

uniform.py
import random # Random float between 1.5 and 9.5 value = random.uniform(1.5, 9.5) print(f"{value:.2f}") # Random temperature between 20.0 and 30.0 temperature = random.uniform(20.0, 30.0) print(f"Temperature: {temperature:.1f}°C") # Random price between 10.99 and 99.99 price = random.uniform(10.99, 99.99) print(f"Price: ${price:.2f}")

random.choice() - Random Selection

The random.choice(sequence) function returns a random element from a sequence (list, tuple, or string). This is perfect for randomly selecting items.

choice.py
import random # Random choice from a list colors = ["red", "blue", "green", "yellow"] selected = random.choice(colors) print(selected) # Random choice from a string letter = random.choice("ABCDEFG") print(f"Random letter: {letter}") # Random choice from a tuple options = ("heads", "tails") coin_flip = random.choice(options) print(f"Coin flip: {coin_flip}")

random.shuffle() - Shuffle Lists

The random.shuffle(list) function randomly reorders the elements in a list. The list is modified in place, meaning the original list is changed.

shuffle.py
import random # Shuffle a list cards = ["Ace", "King", "Queen", "Jack"] print("Before:", cards) random.shuffle(cards) print("After:", cards) # Shuffle numbers numbers = [1, 2, 3, 4, 5] random.shuffle(numbers) print(numbers)

⚠️ Important Note

random.shuffle() modifies the original list and returns None. Don't try to assign its result to a variable!

Common Random Patterns

Here are some common patterns for using random numbers in real programs:

patterns.py
import random # Pattern 1: Random ID generation user_id = random.randint(1000, 9999) print(f"User ID: {user_id}") # Pattern 2: Random delay/timing delay = random.uniform(0.5, 2.0) print(f"Delay: {delay:.2f} seconds") # Pattern 3: Generate multiple random numbers random_numbers = [] for i in range(5): random_numbers.append(random.randint(1, 50)) print(f"Random list: {random_numbers}")

Best Practices

✅ When to Use Each Function

randint() - for whole numbers (dice, scores, counts)

random() - for probabilities and 0-1 ranges

uniform() - for decimal ranges (temperatures, prices)

choice() - for selecting from options

shuffle() - for randomizing order

💡 Important Reminders

• Always import random at the top of your file

randint(a, b) includes both endpoints (inclusive)

random() returns values between 0.0 and 1.0 (exclusive of 1.0)

shuffle() modifies the list in place

🎉

Lesson Complete!

Great work! Continue to the next lesson.

main.py
📤 Output
Click "Run" to execute...