🎲 Python Tutorial — Random Module
Introduction 🌟
The random module in Python is used to generate random numbers, pick random items, shuffle sequences, and simulate randomness. It is widely used in games, simulations, security, testing, AI, and statistical sampling.
Note
💡 The random module generates **pseudo-random** numbers
💡 Based on a deterministic algorithm but unpredictable enough for most applications
💡 Based on a deterministic algorithm but unpredictable enough for most applications
1. Importing the Random Module 🧱
import_random.py
import random2. Generate Random Numbers 🔢
Random Float (0 to 1)
random_float.py
print(random.random()) # Example: 0.73542Random Float in a Range
uniform_range.py
print(random.uniform(1, 10)) # Example: 4.23Random Integer in a Range
randint_example.py
print(random.randint(1, 10)) # 1 to 10 inclusiveRandom Number with Step
randrange_example.py
print(random.randrange(0, 20, 2)) # Even numbers only3. Random Choice Functions 🎯
Pick One Random Element
choice_example.py
items = ["apple", "banana", "cherry"]
print(random.choice(items))Pick Multiple Random Elements
choices_example.py
print(random.choices([1, 2, 3, 4], k=3))Pick Multiple Unique Elements
sample_example.py
print(random.sample([1, 2, 3, 4], 2)) # no duplicates✔ sample() → unique picks
✔ choices() → allows repeats
4. Shuffle a List 🔀
shuffle_example.py
nums = [1, 2, 3, 4, 5]
random.shuffle(nums)
print(nums)✔ Shuffles in place (modifies original list)
5. Random Distribution Functions 📊
Normal Distribution
normalvariate.py
print(random.normalvariate(0, 1)) # mean=0, std=1Gaussian Distribution
gauss_example.py
print(random.gauss(50, 10))Exponential Distribution
expovariate.py
print(random.expovariate(1/5)) # mean = 5Uniform Distribution
uniform_distribution.py
print(random.uniform(10, 20))6. Random Boolean Values ✔️❌
bool_random.py
print(random.choice([True, False]))randrange_bool.py
print(bool(random.getrandbits(1))) # 0 or 17. Seeding the Random Generator 🌱
seed_example.py
random.seed(10)
print(random.random())✔ Seeding ensures repeatable results
✔ Useful for testing and debugging
8. Generate Secure Random Values 🔐
For cryptography, DO NOT use random. Use the secrets module instead.
secure_random.py
import secrets
print(secrets.token_hex(16)) # safe for passwords, keysNote
⚠️ random is NOT secure for passwords or authentication.
9. Real-World Example — Rolling Dice 🎲
dice_roll.py
def roll_dice():
return random.randint(1, 6)
print(roll_dice())10. Real-World Example — Simple Lottery System 🎟️
lottery_system.py
lottery_numbers = random.sample(range(1, 50), 6)
print("Your lucky numbers:", lottery_numbers)11. Real-World Example — Password Generator 🔐
password_generator.py
import string
chars = string.ascii_letters + string.digits
password = "".join(random.choices(chars, k=10))
print(password)12. Random Module Cheat Sheet 📘
| Function | Description |
|---|---|
| random() | Float 0–1 |
| uniform(a,b) | Float in range |
| randint(a,b) | Integer in range |
| randrange() | Integer with step |
| choice() | Pick one value |
| choices() | Pick many (with repeat) |
| sample() | Pick many (unique) |
| shuffle() | Randomize list |
| normalvariate() | Normal distribution |
| seed() | Set random state |
Best Practices 💡
- ✔ Use random for simulations, games, testing
- ✔ Use secrets for security-critical randomness
- ✔ Seed your generator when you need predictable results
- ✔ For large-scale sampling, prefer random.sample()
Conclusion 🎉
>>“Randomness makes simulations realistic and games exciting — Python’s random module brings unpredictability to your programs.” ✨
You now fully understand the Random module in Python! Want the next topic? Try Statistics Module, OS Module, Sys Module, or File Handling Projects. Just tell me! 😊