Python Random Module
Python Random Module Interview Questions
What is the random module in Python?
The random module provides functions for generating pseudo-random numbers. It's used for simulations, games, testing, and any application requiring randomness. Import using import random.
What is random.random() function?
random.random() returns a random float number between 0.0 and 1.0 (inclusive of 0.0, exclusive of 1.0). Example: random.random() might return 0.548813.
What is random.randint() function?
random.randint(a, b) returns a random integer N such that a ≤ N ≤ b. Both endpoints are inclusive. Example: random.randint(1, 10) returns integer between 1 and 10.
What is random.randrange() function?
random.randrange(start, stop, step) returns a randomly selected element from range(start, stop, step). Example: random.randrange(0, 100, 5) returns 0, 5, 10, ..., 95.
What is random.choice() function?
random.choice(seq) returns a random element from a non-empty sequence (list, tuple, string). Example: random.choice(['apple', 'banana', 'cherry']) returns random fruit.
What is random.choices() function?
random.choices(population, weights=None, k=1) returns k sized list of elements chosen from population with replacement. Optional weights for probabilities. Example: random.choices([1,2,3], k=2) returns [2,1].
What is random.sample() function?
random.sample(population, k) returns k unique random elements from population without replacement. Population must be large enough. Example: random.sample(range(100), 5) returns 5 unique numbers.
What is random.shuffle() function?
random.shuffle(x) shuffles the sequence x in place. Returns None. Only works on mutable sequences. Example: cards = [1,2,3,4,5]; random.shuffle(cards) shuffles the list.
What is random.uniform() function?
random.uniform(a, b) returns a random float N such that a ≤ N ≤ b for a ≤ b, and b ≤ N ≤ a for b < a. Example: random.uniform(1.5, 10.5) returns float between 1.5 and 10.5.
How to generate random numbers with normal distribution?
Use random.gauss(mu, sigma) or random.normalvariate(mu, sigma) for normal distribution with mean mu and standard deviation sigma. random.gauss() is slightly faster.
What is seed() function and why use it?
random.seed(a=None) initializes the random number generator with seed value. Same seed produces same sequence of random numbers, useful for reproducibility in testing and debugging.
How to generate random strings?
Combine random.choice() with string constants. Example: import string; ''.join(random.choice(string.ascii_letters) for _ in range(10)) generates 10-character random string.
What are random.getstate() and random.setstate()?
getstate() returns current internal state of generator. setstate(state) restores state. Useful for capturing and restoring random generator state for reproducible sequences.
How to generate random booleans?
Use random.choice([True, False]) or random.getrandbits(1) or bool(random.getrandbits(1)). For weighted probability: random.random() < 0.7 gives True 70% of time.
What is random.triangular() function?
random.triangular(low, high, mode) returns random float from triangular distribution. Mode is the peak. Example: random.triangular(0, 1, 0.5) returns values around 0.5.
How to generate random colors in RGB format?
Use random.randint(0, 255) for each channel: color = (random.randint(0,255), random.randint(0,255), random.randint(0,255)). Or use random.random() for normalized values.
What is the difference between random and secrets modules?
random is for general-purpose pseudo-randomness. secrets (Python 3.6+) is for cryptographic security - uses system's secure random source. Use secrets for passwords, tokens, cryptography.
How to create weighted random choices?
Use random.choices() with weights parameter. Example: random.choices(['A','B','C'], weights=[0.5, 0.3, 0.2], k=10) gives A 50%, B 30%, C 20% probability.
How to generate random dates?
Combine with datetime module: import datetime; start = datetime.date(2020,1,1); end = datetime.date(2023,12,31); random_date = start + datetime.timedelta(days=random.randint(0, (end-start).days)).
What are common use cases for random module?
1. Games (dice rolls, card shuffling)
2. Simulations and Monte Carlo methods
3. Testing with random data
4. Random sampling from datasets
5. Generating test data
6. Randomizing order (shuffle)
7. Password/token generation (use secrets for security)
8. Randomized algorithms
2. Simulations and Monte Carlo methods
3. Testing with random data
4. Random sampling from datasets
5. Generating test data
6. Randomizing order (shuffle)
7. Password/token generation (use secrets for security)
8. Randomized algorithms
Note: Python's random module generates pseudo-random numbers, not truly random. For reproducibility, use seed(). For cryptographic security, use the secrets module. Most functions accept optional parameters for customization. Remember that shuffle() modifies the list in-place while sample() returns a new list.