Python Random Module – Complete Guide with Examples

Introduction

Random numbers play an important role in modern programming. They are widely used in games, simulations, lotteries, password generators, cryptography, machine learning, testing, and many other applications.

Instead of manually generating unpredictable values, Python provides a built-in module called the Random Module that helps developers generate random numbers and make random selections easily.

📖
The Python Random Module offers functions for:
  • Generating random integers
  • Generating random floating-point numbers
  • Selecting random items from lists
  • Shuffling data
  • Creating random samples
  • Generating random passwords and codes

Note: Since the Random Module is included in Python’s standard library, there is no need to install any additional packages.

What is the Python Random Module?

The Random Module is a built-in Python module used for generating pseudo-random numbers and performing random operations.

A pseudo-random number is generated using a mathematical algorithm that produces values that appear random.

Note: Before using the module, it must be imported.

Importing the Random Module

Syntax:


import random

Example:


import random
print(random.random())

Output:

0.547892314

(The output will vary each time.)

Generating Random Float Numbers

The random() function returns a floating-point number between 0 and 1.

Syntax:


random.random()

Example:


import random
print(random.random())

Output:

0.7865234

The value will always be 0 <= value < 1

Generating Random Integers

The randint() function generates a random integer within a specified range.

Syntax:


random.randint(start, end)

Example:


import random
print(
    random.randint(1, 10)
)

Output:

7

The result can be any number from 1 to 10 including both endpoints.

Generating Random Numbers with randrange()

The randrange() function works similarly to Python’s range().

Syntax:


random.randrange(
    start,
    stop,
    step
)

Example:


import random
print(
    random.randrange(
        1,
        20,
        2
    )
)

Output:


13

Possible values 1, 3, 5, 7, 9, ...

Generating Random Floating Numbers in a Range

The uniform() function generates a random floating-point number within a range.

Syntax:


random.uniform(a, b)

Example:


import random
print(
    random.uniform(
        1,
        10
    )
)

Output:

5.734892

Choosing a Random Element

The choice() function selects a random element from a sequence.

Syntax:


random.choice(sequence)

Example:


import random
colors = [
    "Red",
    "Blue",
    "Green"
]
print(
    random.choice(colors)
)

Output:

Blue

Choosing Multiple Random Elements

The choices() function selects multiple random elements.

Syntax:


random.choices(
    sequence,
    k=count
)

Example:


import random
fruits = [
    "Apple",
    "Banana",
    "Mango"
]
result = random.choices(
    fruits,
    k=3
)
print(result)

Output:

[‘Apple’, ‘Mango’, ‘Banana’]

Duplicates are possible.

Selecting Unique Random Elements

The sample() function returns unique random elements.

Syntax:


random.sample(
    sequence,
    count
)

Example:


import random
numbers = [
    1,2,3,4,5
]
print(
    random.sample(
        numbers,
        3
    )
)

Output:

[4, 1, 5]

No duplicates are included.

Shuffling a List

The shuffle() function randomly rearranges elements.

Syntax:


random.shuffle(list)

Example:


import random
cards = [
    "A",
    "K",
    "Q",
    "J"
]
random.shuffle(cards)
print(cards)

Output:

[‘Q’, ‘A’, ‘J’, ‘K’]

Order changes each time.

Setting a Seed Value

The seed() function initializes the random number generator.

Syntax:


random.seed(value)

Example:


import random
random.seed(10)
print(
    random.randint(1, 100)
)

Output:

74

Running the program again with the same seed produces the same result.

Why Use seed()?

Useful for:

  • Testing
  • Debugging
  • Reproducible results
  • Scientific simulations

Random Boolean Values

Example:


import random
print(
    random.choice(
        [True, False]
    )
)

Output:

True
or
False

Random Password Generator

Example:


import random
characters = (
    "abcdefghijklmnopqrstuvwxyz"
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    "1234567890"
)
password = ""
for i in range(8):
    password += random.choice(
        characters
    )
print(password)

Output:

A8xP2qMz

Useful for creating temporary passwords.

Simulating a Dice Roll

Example:


import random
dice = random.randint(
    1,
    6
)
print(dice)

Output:

4

Possible values 1 to 6.

Simulating a Coin Toss

Example:


import random
result = random.choice(
    ["Heads", "Tails"]
)
print(result)

Output:

Heads

Generating Random OTP

Example:


import random
otp = random.randint(
    1000,
    9999
)
print(otp)

Output:

4837

Useful for authentication systems.

Real-Life Example: Lottery System


import random
numbers = range(1, 51)
lottery = random.sample(
    numbers,
    6
)
print(lottery)

Output:

[4, 12, 18, 27, 35, 49]

Six unique lottery numbers are selected.

Real-Life Example: Student Picker


import random
students = [
    "John",
    "Mike",
    "Sara",
    "Emma"
]
selected = random.choice(
    students
)
print(selected)

Output:

Sara

Real-Life Example: Random Discount Generator


import random
discount = random.choice(
    [5, 10, 15, 20]
)
print(
    f"{discount}% OFF"
)

Output:

15% OFF

Real-Life Example: Quiz Application


import random
questions = [
    "Q1",
    "Q2",
    "Q3",
    "Q4"
]
random.shuffle(
    questions
)
print(questions)

Output:

[‘Q3’, ‘Q1’, ‘Q4’, ‘Q2’]

Questions appear in a different order each time.

Commonly Used Random Functions

Function Description
random() Random float between 0 and 1
randint() Random integer
randrange() Random number from range
uniform() Random float in range
choice() Random item
choices() Multiple random items
sample() Unique random items
shuffle() Randomly reorder list
seed() Initialize random generator

Advantages of Python Random Module

Advantage Description
Built-in No installation required
Easy to Use Simple syntax
Fast Efficient random generation
Versatile Supports many random operations
Useful in Testing Generates random test data

Common Mistakes

1. Forgetting to Import random

Incorrect:


print(
    random.randint(1, 10)
)

Output:

NameError

Correct:


import random

2. Using choice() on an Empty List

Incorrect:


random.choice([])

Output:

IndexError

Always ensure the sequence contains data.

3. Requesting Too Many Samples

Incorrect:


random.sample(
    [1,2,3],
    5
)

Output:

ValueError

Cannot select more unique elements than available.

4. Expecting Truly Random Values

Python’s Random Module generates pseudo-random numbers, not true randomness.

5. Using Random Module for Security

Avoid:


random.randint()

for secure passwords or tokens.

Use:


secrets

module instead.

Best Practices

1. Import the Module Once


import random

at the top of the file.

2. Use Meaningful Variable Names

Good:


dice_roll
selected_student
random_password

3. Use sample() for Unique Values

Avoid duplicates when uniqueness is required.

4. Use seed() During Testing

Produces consistent results.

5. Use the secrets Module for Security

For secure passwords and authentication systems.

Conclusion

The Python Random Module is a powerful built-in library that simplifies the generation of random numbers and random selections. It provides functions for creating random integers, floating-point values, samples, shuffled data, and random choices from sequences.

The module is widely used in games, simulations, testing, data analysis, lotteries, and educational applications. By understanding functions such as random(), randint(), choice(), sample(), shuffle(), and seed(), developers can easily add randomness and unpredictability to their Python programs.

Related Python Tutorials