Here are 10 Python code snippets demonstrating how to use Python's random module to generate pseudo-random numbers and perform various random operations.
1. Generating a Random Integer
Copy
import random
# Generate a random integer between 1 and 100
random_integer = random.randint(1, 100)
print(f"Random Integer: {random_integer}")
2. Generating a Random Float
Copy
import random
# Generate a random float between 0 and 1
random_float = random.random()
print(f"Random Float: {random_float}")
3. Selecting a Random Item from a List
Copy
4. Selecting Multiple Random Items
Copy
5. Shuffling a List
Copy
6. Generating a Random Range
Copy
7. Generating Random Numbers with a Normal Distribution
Copy
8. Generating a Random Boolean
Copy
9. Generating a Random String
Copy
10. Generating Reproducible Random Results
Copy
Summary:
The random module provides tools for:
Generating random numbers (randint, random, randrange).
Random selection (choice, sample).
Shuffling (shuffle).
Advanced distributions (e.g., gauss).
Creating reproducible random results using seed.
Let me know if you'd like detailed explanations for any of these functions!
import random
# Randomly select an item from a list
choices = ['apple', 'banana', 'cherry', 'date']
random_item = random.choice(choices)
print(f"Random Choice: {random_item}")
import random
# Randomly select 3 items from a list
choices = ['apple', 'banana', 'cherry', 'date', 'elderberry']
random_items = random.sample(choices, 3)
print(f"Random Sample: {random_items}")
import random
# Shuffle the elements in a list
numbers = [1, 2, 3, 4, 5]
random.shuffle(numbers)
print(f"Shuffled List: {numbers}")
import random
# Generate a random number from a range with a step
random_range = random.randrange(10, 50, 5)
print(f"Random Number from Range: {random_range}")
import random
# Generate a random number with mean=0 and standard deviation=1
random_normal = random.gauss(mu=0, sigma=1)
print(f"Random Number (Normal Distribution): {random_normal}")
import random
# Randomly generate True or False
random_boolean = random.choice([True, False])
print(f"Random Boolean: {random_boolean}")
import random
import string
# Generate a random string of 8 characters
random_string = ''.join(random.choices(string.ascii_letters + string.digits, k=8))
print(f"Random String: {random_string}")
import random
# Set the seed for reproducibility
random.seed(42)
# Generate random numbers
print(f"Random Number 1: {random.randint(1, 100)}")
print(f"Random Number 2: {random.randint(1, 100)}")