General Programming & Random Module
Goal: Understand programming paradigms (static vs. dynamic typing)
and leverage Python’s random module for randomness in applications.
1. Statically Typed vs. Dynamically Typed Languages
Key Differences:
Statically Typed (e.g., Java, C++, Dynamically Typed (e.g., Python,
Feature
Kotlin) JavaScript)
Type
At compile-time At runtime
Checking
Less flexible (types declared More flexible (types inferred at
Flexibility
upfront) runtime)
Error
Early (during compilation) During execution
Detection
Examples int x = 5; (explicit) x = 5 (implicit)
Python’s Dynamic Typing:
Variables can change types freely:
x = 10 # x is an integer
x = "hello" # Now x is a string
Type Hints (Python 3.5+):
Optional annotations for readability:
def greet(name: str) -> str:
return f"Hello, {name}"
2. The random Module
Generates pseudo-random numbers for games, simulations, or data
sampling.
Importing the Module:
import random
3. Common random Functions
1. random.random():
o Returns a float between 0.0 (inclusive) and 1.0 (exclusive).
o Example:
python
Copy
Download
x = random.random() # e.g., 0.548, 0.001
2. random.randint(a, b):
o Returns a random integer between a and b (inclusive).
o Example:
python
Copy
Download
dice_roll = random.randint(1, 6) # 1, 2, 3, 4, 5, or 6
3. random.uniform(a, b):
o Returns a float between a and b.
o Example:
python
Copy
Download
temp = random.uniform(-5.0, 10.0) # e.g., 3.7, -2.4
4. random.choice(sequence):
o Picks a random item from a non-empty sequence (list, tuple,
string).
o Example:
colors = ["red", "green", "blue"]
winner = random.choice(colors) # e.g., "green"
5. random.sample(population, k):
o Returns a list of k unique elements from the population.
o Example:
numbers = [1, 2, 3, 4, 5]
selected = random.sample(numbers, 3) # e.g., [3, 1, 5]
6. random.shuffle(sequence):
o Shuffles a list in place.
o Example:
cards = ["Ace", "King", "Queen"]
random.shuffle(cards) # e.g., ["King", "Ace", "Queen"]
4. Seeding for Reproducibility
Use random.seed() to generate the same "random" sequence every
time (useful for debugging).
random.seed(42)
print(random.randint(1, 100)) # Always 82 with seed 42
5. Common Mistakes
1. Forgetting to Import random:
x = random() # NameError: 'random' is not defined
2. Misusing choice on Empty Sequences:
empty_list = []
random.choice(empty_list) # IndexError
3. Confusing sample with choices:
o sample(): Unique elements.
o choices(): Allows duplicates (requires k argument).
4. Assuming Uniform Distribution:
o random uses pseudo-randomness, not true randomness.
6. Practical Applications
1. Password Generator:
import random
import string
def generate_password(length=8):
chars = string.ascii_letters + string.digits
return ''.join(random.choice(chars) for _ in range(length))
print(generate_password()) # e.g., "a3Fg9T2x"
2. Random Sampling for Data Analysis:
data = [10, 20, 30, 40, 50]
sample = random.sample(data, 2) # e.g., [30, 10]
3. Dice Game Simulation:
def roll_dice():
return random.randint(1, 6) + random.randint(1, 6)
print(roll_dice()) # Sum of two dice (e.g., 7)
7. Key Takeaways
1. Static vs. Dynamic Typing:
o Python is dynamically typed (flexible but requires careful
testing).
o Use type hints for clarity.
2. random Module:
o Use randint() for integers, uniform() for floats.
o choice() and sample() are ideal for random selections.
3. Seed for Consistency:
o Critical for debugging randomized algorithms.