Python
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax and Data Types
-
Section 3: Collections
-
39: Set Operations: Union, Intersection, Difference
-
Section 4: Control Flow
-
Section 5: Functions
-
Section 6: Turtle Graphics and Early Practice Projects
-
Section 7: Working with Files and I/O
-
Section 8: Regular Expressions
-
Section 9: Object-Oriented Python
-
Section 10: Error Handling
-
Section 11: Modules and Packages
-
Section 12: Iterators, Generators, and Functional Tools
-
Section 13: Decorators and Metaprogramming
-
Section 14: Concurrency and Parallelism
-
Section 15: Working with Dates, Times, and Numbers
-
Section 16: Standard Library Deep Dive I: Data Structures
-
Section 17: Standard Library Deep Dive II: System and Introspection
-
Section 18: Standard Library Deep Dive III: Security and Encoding
-
Section 19: Standard Library Deep Dive IV: Text and Data Utilities
-
Section 20: Networking and Web Basics
-
Section 21: Working with Databases
-
Section 22: Testing and Quality
-
Section 23: Advanced Typing
-
Section 24: Context Managers and Resource Handling
-
Section 25: Text, Unicode, and Binary Data
-
Section 26: More Functional and Iteration Tools
-
Section 27: Data Validation and Configuration
-
Section 28: Working with Images and Media
-
Section 29: Property-Based and Documentation Testing
-
Section 30: Packaging and Deployment
-
Section 31: Performance and Internals
-
Section 32: Design Patterns in Python
-
Section 33: GUI Programming
-
Section 34: Security Basics
-
Section 35: Data Structures and Algorithms
-
Section 36: Practical Projects
-
Section 37: Capstone Projects
-
Section 38: Interview and Algorithm Practice
-
Section 39: Writing Idiomatic Python
226: The random Module and Seeding
How do I actually pick a random number or a random item from a list?
Depending on what you're building, you'll usually reach for one of three tools. If you need a floating-point number between 0 and 1, random.random() is your go-to. But most of the time, you want integers. I usually use random.randint(a, b) because it's inclusive—if you tell it 1 to 20, you can actually get a 1 or a 20, which is exactly how a 20-sided die works in a tabletop game.
If you have a list of options and just need one of them, don't bother generating a random index manually. Just use random.choice(). It's much cleaner.
import random
# Rolling a D20 for a critical hit check
roll = random.randint(1, 20)
print(f"You rolled a {roll}!")
# Picking a random magic item from a chest
loot_table = ["Rusty Sword", "Health Potion", "Ancient Map", "Piece of Lint"]
item = random.choice(loot_table)
print(f"You found a {item}!")
Is there a difference between choosing one item and shuffling the whole list?
Absolutely. random.choice() just grabs one element and leaves the original list alone. But if you're building something like a card game or a randomized playlist, you want random.shuffle(). One thing to watch out for: shuffle() modifies the list in place. It doesn't return a new list; it rearranges the one you already have. I've seen plenty of beginners try to assign the result to a variable, only to find out their variable is None.
import random
players = ["Alice", "Bob", "Charlie", "Diana"]
# This rearranges the actual list
random.shuffle(players)
print(f"The turn order is: {players}")
What's the deal with random.seed()? Why would I want "predictable" randomness?
It sounds like a contradiction, right? "Predictable randomness." But here is the secret: computers aren't actually random. They use mathematical formulas to generate a sequence of numbers that look random. This is called pseudo-randomness. The seed is the starting point for that formula.
If you use the same seed, you get the exact same sequence of "random" numbers every single time. This is a lifesaver for debugging. Imagine you're simulating a complex stock market crash or generating a procedural map for a game. If a weird bug happens on "Map #402," you don't want to spend three hours trying to randomly stumble upon that exact map again. You just hardcode the seed, and the "random" generation becomes deterministic.
import random
# Set the seed to something specific
random.seed(42)
print(random.random()) # This will always be 0.6394267984578837
print(random.random()) # This will always be 0.02501075522266693
# Resetting the seed restarts the sequence
random.seed(42)
print(random.random()) # Back to 0.6394267984578837
📋 Practical Task
The Procedural Dungeon Room Generator
You are building a roguelike game where each room is generated based on a "Room ID" (which serves as your seed). This ensures that if a player shares a Room ID with a friend, the friend sees the exact same room layout.
Your Task: Write a function called generate_room(room_id) that does the following:
- Sets the
random.seed()using the providedroom_id. - Randomly selects one "Enemy" from a list:
["Goblin", "Skeleton", "Slime", "Orc"]. - Randomly selects one "Treasure" from a list:
["Gold Coin", "Gemstone", "Old Boot", "Magic Scroll"]. - Generates a random integer between 10 and 50 for the "Room Difficulty".
- Returns these three values as a tuple.
Test your code: Call generate_room(123) twice. If your seeding is correct, both calls should return the exact same enemy, treasure, and difficulty.
There are no comments for now.