Chapter 4: Random Numbers and Games / Lesson 24

Random Event Generator

Creating Random Events

Random events add unpredictability and excitement to programs. By combining random.choice() with lists of options, you can create programs that generate random events, outcomes, and scenarios.

This is useful for games, simulations, decision-making tools, and any program where you want varied, unpredictable behavior based on random selection.

Basic Random Event Generator

Use random.choice() to randomly select from a list of possible events or outcomes:

basic_event.py
import random # List of possible events events = ["Rain", "Sunny", "Cloudy", "Snow"] # Generate a random event today_weather = random.choice(events) print(f"Today's weather: {today_weather}") # Generate multiple random events for day in range(5): weather = random.choice(events) print(f"Day {day + 1}: {weather}")

Random Outcomes with Messages

Combine random selection with formatted messages to create meaningful random events:

outcomes.py
import random # Different types of outcomes outcomes = ["Success!", "Try again", "Almost there", "Great job!"] # Random outcome with message result = random.choice(outcomes) print(f"Your result: {result}") # Coin flip with messages coin_outcomes = ["Heads - You win!", "Tails - Try again"] coin_result = random.choice(coin_outcomes) print(coin_result)

Multiple Random Events

Generate multiple random events in sequence to create more complex scenarios:

multiple_events.py
import random # Adventure game events actions = ["Find treasure", "Meet a friend", "Discover a cave", "See a dragon"] locations = ["forest", "mountain", "beach", "desert"] # Generate random adventure action = random.choice(actions) location = random.choice(locations) print(f"You {action} in the {location}!") # Multiple events in sequence for i in range(3): event = random.choice(actions) place = random.choice(locations) print(f"Event {i+1}: {event} at {place}")

Weighted Random Events

You can create weighted probabilities by repeating items in a list, making some events more likely than others:

weighted.py
import random # Weighted outcomes - "Common" appears 3 times, making it 3x more likely outcomes = ["Common", "Common", "Common", "Rare", "Epic"] # Generate weighted random result result = random.choice(outcomes) print(f"You got: {result}") # Test the distribution results_count = {"Common": 0, "Rare": 0, "Epic": 0} for i in range(100): result = random.choice(outcomes) results_count[result] += 1 print("Distribution (100 trials):", results_count)

Practical Applications

Random event generators are useful in many scenarios:

applications.py
import random # Application 1: Daily motivation motivations = [ "Keep going!", "You've got this!", "Stay strong!", "Believe in yourself!" ] print(f"Today's motivation: {random.choice(motivations)}") # Application 2: Random activity generator activities = ["Read a book", "Go for a walk", "Learn something new", "Call a friend"] print(f"Suggested activity: {random.choice(activities)}") # Application 3: Random story elements characters = ["wizard", "knight", "princess"] settings = ["castle", "forest", "cave"] character = random.choice(characters) setting = random.choice(settings) print(f"Once upon a time, a {character} lived in a {setting}.")

Combining with Conditional Logic

Combine random events with if statements to create different behaviors based on the random outcome:

conditional_events.py
import random # Random event with different responses event = random.choice(["sunny", "rainy", "snowy"]) if event == "sunny": print("Great day for a picnic!") elif event == "rainy": print("Perfect day to stay inside!") else: print("Time to build a snowman!") print(f"Weather: {event}")

Best Practices

✅ Tips for Random Events

• Store event options in lists for easy modification

• Use descriptive variable names for your event lists

• Combine multiple random choices for complex scenarios

• Use weighted lists if you need different probabilities

• Add conditional logic to create dynamic responses

💡 Remember

Each call to random.choice() gives a new random result. The same list can produce different outcomes every time you run the program!

🎉

Lesson Complete!

Great work! Continue to the next lesson.

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