Popular Searches
Popular Course Categories
Popular Courses

Generating Random Values Using random

Generating Random Values Using random

Regular Expressions, Date and Time, and Utility Modules

Generating Random Values Using Python's random Module

Course: Python Training

Topic: Generating Random Values Using random

Course URL: Python Training Course

Demo URL: Register for a Course Demo

Learning Platform: JustAcademy Official Website


1. Introduction to Random Value Generation

Random value generation is an important programming technique used to produce values that are difficult to predict in advance. Python provides a built-in module called random for generating pseudorandom numbers, selecting random items from sequences, shuffling lists, and simulating random events.

The random module is useful for games, simulations, testing, sample-data generation, randomized quizzes, probability experiments, and educational applications.

Python's standard random module uses a pseudorandom number generator. Its output appears random for many practical applications, but it is generated algorithmically and can be reproduced when the same seed and compatible execution conditions are used.

Example

import random

number = random.randint(1, 100)

print("Random number:", number)

Each execution can produce a different integer between 1 and 100, including both endpoints.

2. Learning Objectives

  • Understand random and pseudorandom values.
  • Import and use Python's random module.
  • Generate random integers and floating-point numbers.
  • Choose random elements from lists and other sequences.
  • Generate multiple selections with and without replacement.
  • Shuffle lists and understand how the original sequence changes.
  • Use random seeds for reproducible experiments.
  • Generate values according to probability distributions.
  • Handle common errors when using random functions.
  • Understand when to use secrets instead of random.

3. Importing the random Module

The random module is included in Python's standard library. You do not normally need to install an additional package to use it.

import random

value = random.random()

print(value)

The statement import random makes the module's functions available through the random namespace.

Importing Specific Functions

from random import randint, choice

number = randint(1, 10)
color = choice(["red", "blue", "green"])

print(number)
print(color)

Importing specific functions can be convenient, although importing the module itself often makes the origin of each function clearer.

4. Understanding Pseudorandom Numbers

A pseudorandom number generator produces a sequence of values using an algorithm and an internal state. The values are designed to have useful statistical properties, but the sequence is deterministic when its initial state is known.

Key Characteristics

Characteristic Explanation
Algorithm-based Values are produced through a mathematical process.
Appears random The generated sequence can be suitable for simulations and many ordinary programming tasks.
Seed-dependent A known seed can make the generated sequence reproducible.
Efficient Random values can be generated quickly.
Not cryptographically secure The standard generator should not be used for passwords, authentication tokens, or security-sensitive secrets.

Python's random module uses the Mersenne Twister algorithm for its standard generator. It is suitable for many simulations and general-purpose tasks, but not for cryptographic security. Read the official Python random documentation.

5. Generating Random Floating-Point Numbers with random()

The random.random() function returns a floating-point number in the range from 0.0 inclusive to 1.0 exclusive.

Mathematically, the result satisfies:

0.0 <= value < 1.0

Example

import random

number = random.random()

print(number)

A possible result is 0.472813. Your result will usually be different.

Generate Multiple Random Floats

import random

for index in range(5):
    print(random.random())

This loop generates five random floating-point values.

Use Cases

  • Simulating probability experiments.
  • Generating normalized values between zero and one.
  • Creating randomized test inputs.
  • Implementing simple game mechanics.

6. Generating Random Integers with randint()

The random.randint(a, b) function returns a random integer from a through b, inclusive. Both endpoints are possible results.

Example

import random

number = random.randint(1, 10)

print(number)

The result can be any integer from 1 to 10, including 1 and 10.

Simulating a Dice Roll

import random

dice_roll = random.randint(1, 6)

print("Dice result:", dice_roll)

This program simulates a standard six-sided die.

Generating Random Marks

import random

marks = random.randint(0, 100)

print("Student marks:", marks)

The example generates an integer score between 0 and 100.

Important Difference

randint(1, 10) includes 10. This differs from Python's range(1, 10), which excludes 10.

7. Generating Integers with randrange()

The random.randrange() function chooses a value from a range-like sequence. It supports a start, stop, and optional step, similar to the built-in range() function.

7.1 Random Integer from Zero to Nine

import random

number = random.randrange(10)

print(number)

The possible results are 0 through 9.

7.2 Random Integer within a Range

import random

number = random.randrange(10, 21)

print(number)

The result is an integer from 10 through 20. The stop value, 21, is excluded.

7.3 Generate Random Even Numbers

import random

number = random.randrange(2, 21, 2)

print(number)

The possible results are 2, 4, 6, 8, 10, 12, 14, 16, 18, and 20.

7.4 Generate Random Odd Numbers

import random

number = random.randrange(1, 20, 2)

print(number)

The possible results are 1, 3, 5, 7, 9, 11, 13, 15, 17, and 19.

randint() vs. randrange()

Function Range Behavior Example
randint(1, 6) Both endpoints included 1 through 6
randrange(1, 6) Stop value excluded 1 through 5
randrange(0, 20, 5) Uses the specified step 0, 5, 10, 15

8. Generating Random Floating-Point Values with uniform()

The random.uniform(a, b) function generates a floating-point value between two specified bounds. It is useful when a random decimal value is needed rather than an integer.

Example

import random

temperature = random.uniform(20.0, 30.0)

print("Temperature:", temperature)

The generated value lies between the supplied bounds. Because floating-point values have finite precision, endpoint behavior should not be relied upon for strict boundary validation.

Generate a Random Price

import random

price = random.uniform(100.0, 500.0)

print(f"Generated price: ₹{price:.2f}")

The format specifier :.2f displays the number with two digits after the decimal point. It changes the display format, not the precision of the underlying value.

Generate Random Measurements

import random

for _ in range(3):
    measurement = random.uniform(1.5, 5.5)
    print(round(measurement, 2))

9. Selecting a Random Element with choice()

The random.choice(sequence) function selects one item from a non-empty sequence, such as a list, tuple, or string.

Example: Random Color

import random

colors = ["red", "green", "blue", "yellow"]

selected_color = random.choice(colors)

print("Selected color:", selected_color)

Example: Random Name

import random

students = ["Asha", "Rahul", "Neha", "Arjun"]

winner = random.choice(students)

print("Selected student:", winner)

Example: Random Character

import random

letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

letter = random.choice(letters)

print("Selected letter:", letter)

If the sequence is empty, random.choice() raises an IndexError. Validate that the sequence contains at least one item when emptiness is possible.

10. Selecting Multiple Items with choices()

The random.choices() function selects one or more items from a population. It samples with replacement, which means the same item can be selected more than once.

Example

import random

colors = ["red", "green", "blue"]

selected_colors = random.choices(colors, k=5)

print(selected_colors)

The result contains five selections. Repeated colors are allowed.

Weighted Random Selection

You can use the weights parameter to assign different relative chances to each item.

import random

prizes = ["Small Prize", "Medium Prize", "Grand Prize"]
weights = [70, 25, 5]

selected_prize = random.choices(
    prizes,
    weights=weights,
    k=1
)[0]

print("Prize:", selected_prize)

The weights are relative, not percentages that must add up to 100. Here, the relative weights are 70, 25, and 5. A larger weight gives an item a greater chance of selection, but does not guarantee a particular result in a single draw.

When to Use choices()

  • Simulating repeated events where outcomes can recur.
  • Generating random survey responses.
  • Simulating weighted outcomes in a simple model.
  • Creating randomized sample data.

11. Selecting Unique Items with sample()

The random.sample(population, k) function selects k items without replacement. It returns a new list and leaves the original population unchanged.

Example

import random

numbers = [10, 20, 30, 40, 50, 60]

selected_numbers = random.sample(numbers, k=3)

print("Selected:", selected_numbers)
print("Original:", numbers)

The selected items are unique by population position. If the population contains duplicate values, equal values can still appear more than once because they may represent separate occurrences in the population.

Example: Selecting Raffle Winners

import random

participants = [
    "Asha",
    "Rahul",
    "Neha",
    "Arjun",
    "Priya"
]

winners = random.sample(participants, k=2)

print("Winners:", winners)

Two distinct participant entries are selected without replacement. Ensure that k does not exceed the population size; otherwise, random.sample() raises a ValueError.

choice() vs. choices() vs. sample()

Function Number of Results Replacement Returns
choice(items) One item One selection One item
choices(items, k=5) Five items With replacement List
sample(items, k=5) Five items Without replacement List

12. Shuffling a List with shuffle()

The random.shuffle() function randomly rearranges the elements of a mutable sequence, such as a list. It modifies the original list in place and returns None.

Example

import random

cards = ["Ace", "King", "Queen", "Jack"]

random.shuffle(cards)

print(cards)

The list contains the same elements, but their order may change.

Shuffle a Quiz

import random

questions = [
    "What is Python?",
    "What is a function?",
    "What is a list?",
    "What is a dictionary?"
]

random.shuffle(questions)

for number, question in enumerate(questions, start=1):
    print(f"{number}. {question}")

Important Note

Do not write shuffled = random.shuffle(cards) when you expect a shuffled list to be returned. The function returns None. If you need a new shuffled list while preserving the original, use random.sample(cards, k=len(cards)).

13. Setting a Random Seed with seed()

The random.seed() function initializes the pseudorandom number generator. Using the same seed can reproduce the same sequence of values under compatible conditions. This is helpful for testing, simulations, demonstrations, and machine-learning experiments.

Example

import random

random.seed(42)

print(random.randint(1, 100))
print(random.randint(1, 100))
print(random.random())

Running the same code with the same seed and compatible Python implementation should reproduce the sequence. Do not rely on every function's sequence remaining identical across all Python versions.

Compare Results with Different Seeds

import random

random.seed(10)
first_value = random.random()

random.seed(20)
second_value = random.random()

print(first_value)
print(second_value)

Different seeds generally produce different pseudorandom sequences.

Why Use a Seed?

  • Reproduce a simulation during debugging.
  • Generate repeatable test data.
  • Compare algorithm performance using the same random inputs.
  • Make educational examples easier to verify.

A fixed seed is useful for reproducibility, but it does not make generated values secret or secure.

14. Generating Random Values from Probability Distributions

The random module provides functions for generating values from several statistical distributions. These functions are useful in simulation and statistical modeling when their assumptions match the problem.

Function Purpose Example
random.uniform(a, b) Uniform distribution over an interval random.uniform(0, 10)
random.gauss(mu, sigma) Gaussian (normal) distribution random.gauss(100, 15)
random.normalvariate(mu, sigma) Normal distribution random.normalvariate(50, 5)
random.expovariate(lambd) Exponential distribution random.expovariate(0.5)
random.triangular(low, high, mode) Triangular distribution random.triangular(1, 10, 4)

14.1 Normal Distribution

import random

test_score = random.gauss(70, 10)

print("Simulated score:", round(test_score, 2))

The first argument is the mean and the second is the standard deviation. A normal distribution has no strict lower or upper bound, so a generated score can fall outside a range such as 0 to 100. Apply suitable validation or use a different model if the values represent bounded scores.

14.2 Exponential Distribution

import random

average_rate = 0.5

waiting_time = random.expovariate(average_rate)

print("Simulated waiting time:", waiting_time)

The lambd parameter is a rate and must be greater than zero. The exponential distribution is commonly used to model certain waiting-time processes when its assumptions are appropriate.

15. Creating a Random Number Guessing Game

A number guessing game is a practical way to combine random number generation, loops, conditions, and user input.

Complete Program

import random

def play_guessing_game():
    """Run a number guessing game."""
    secret_number = random.randint(1, 20)
    attempts = 0

    print("Guess a number between 1 and 20.")

    while True:
        user_input = input("Enter your guess: ")

        try:
            guess = int(user_input)
        except ValueError:
            print("Please enter a valid whole number.")
            continue

        if not 1 <= guess <= 20:
            print("Your guess must be between 1 and 20.")
            continue

        attempts += 1

        if guess < secret_number:
            print("Too low. Try again.")
        elif guess > secret_number:
            print("Too high. Try again.")
        else:
            print(f"Correct! Attempts: {attempts}")
            break


if __name__ == "__main__":
    play_guessing_game()

How It Works

  1. The program generates a secret integer between 1 and 20.
  2. The player enters a guess.
  3. The program checks whether the input can be converted to an integer.
  4. It rejects guesses outside the allowed range.
  5. It displays whether the guess is too low or too high.
  6. The loop ends when the player guesses correctly.

16. Practical Project: Random Quiz and Raffle Selector

Create a simple program that can select a random quiz question and select raffle winners without replacement.

import random


def select_random_question(questions):
    """Return one question from a non-empty collection."""
    if not questions:
        raise ValueError("The question list cannot be empty.")

    return random.choice(questions)


def select_raffle_winners(participants, winner_count):
    """Select distinct participant entries as winners."""
    if winner_count < 0:
        raise ValueError("Winner count cannot be negative.")

    if winner_count > len(participants):
        raise ValueError("Not enough participants.")

    return random.sample(participants, k=winner_count)


def main():
    questions = [
        "What is a Python list?",
        "What is a tuple?",
        "What is a dictionary?",
        "What is a Python module?"
    ]

    participants = [
        "Asha",
        "Rahul",
        "Neha",
        "Arjun",
        "Priya"
    ]

    question = select_random_question(questions)
    winners = select_raffle_winners(participants, 2)

    print("Random question:", question)
    print("Raffle winners:", winners)


if __name__ == "__main__":
    main()

Project Concepts Demonstrated

  • Importing and using the random module.
  • Choosing one random item from a sequence.
  • Selecting multiple items without replacement.
  • Validating function inputs.
  • Organizing logic into reusable functions.
  • Using a main function as the program entry point.

17. Common Errors and Troubleshooting

Error or Mistake Cause Solution
IndexError from choice() The sequence is empty. Check that the sequence contains items before choosing.
ValueError from sample() The requested sample size exceeds the population size, or the size is invalid. Validate the sample size before calling the function.
ValueError from randrange() The specified range is empty or invalid. Review the start, stop, and step values.
Unexpected None after shuffling shuffle() modifies a list in place and returns None. Call random.shuffle(items) separately.
Different results on each run The generator state changes between runs. Use a fixed seed when reproducibility is required.
Repeated selections choices() samples with replacement. Use sample() when unique population positions are required.
Using random values for security The standard generator is not designed for cryptographic security. Use Python's secrets module.

18. Best Practices for Using random

  • Import the module explicitly with import random.
  • Choose randint() when both integer endpoints should be included.
  • Choose randrange() when range-style stop and step behavior is useful.
  • Use uniform() for random floating-point values over an interval.
  • Use choice() for one selection, choices() for repeated selections with replacement, and sample() for selections without replacement.
  • Validate collection sizes and numeric bounds when they come from external input.
  • Use a fixed seed only when repeatable pseudorandom output is useful.
  • Keep random generation separate from business logic where that improves testing.
  • Do not assume that randomly generated data automatically represents real-world distributions.
  • Do not use the standard random module to create passwords, authentication tokens, or security-sensitive identifiers.

19. Using secrets for Security-Sensitive Random Values

For passwords, authentication tokens, reset links, and other security-sensitive values, use Python's secrets module instead of random. The secrets module is designed to generate values suitable for security-sensitive use.

Example: Generate a Secure Token

import secrets

token = secrets.token_urlsafe(32)

print(token)

This generates a URL-safe token using a cryptographically secure source. In real applications, handle tokens carefully, store them appropriately, and follow the security requirements of the application.

Example: Choose a Secure Random Number

import secrets

number = secrets.randbelow(100) + 1

print(number)

This generates a secure random integer between 1 and 100, inclusive. Use secrets.randbelow() when the number must be suitable for security-sensitive purposes.

20. Interview Questions and Answers

Q1. What is the Python random module?

The random module is part of Python's standard library and provides functions for generating pseudorandom values, choosing sequence elements, shuffling lists, and sampling populations.

Q2. What is the difference between random() and randint()?

random.random() returns a floating-point value from 0.0 inclusive to 1.0 exclusive. random.randint(a, b) returns an integer between a and b, inclusive.

Q3. What is the difference between randint() and randrange()?

randint(a, b) includes both endpoints. randrange(start, stop, step) follows the behavior of range(), so the stop value is excluded.

Q4. What does uniform() do?

uniform(a, b) generates a floating-point value over an interval defined by the supplied bounds.

Q5. What is the purpose of choice()?

choice() selects one random item from a non-empty sequence.

Q6. What is the difference between choices() and sample()?

choices() samples with replacement, allowing repeated selections. sample() samples without replacement, so it does not select the same population position twice.

Q7. What does shuffle() do?

shuffle() randomly rearranges a mutable sequence in place and returns None.

Q8. Why is seed() used?

seed() initializes the pseudorandom generator and can make results reproducible under compatible conditions.

Q9. What is a pseudorandom number?

A pseudorandom number is generated algorithmically. Its sequence can be deterministic even though the values have random-like properties.

Q10. Is Python's random module cryptographically secure?

No. Use the secrets module for security-sensitive values such as authentication tokens and password-reset tokens.

Q11. What happens if choice() receives an empty list?

It raises an IndexError because there is no item to select.

Q12. What happens if sample() requests too many items?

It raises a ValueError when the requested sample size exceeds the population size.

Q13. How can random values help in testing?

Random values can generate varied test inputs and expose unexpected edge cases. A fixed seed can help reproduce a particular pseudorandom sequence during debugging.

Q14. Can random.choices() use weights?

Yes. The weights parameter allows selections to follow relative weights instead of equal probabilities.

Q15. How can you randomly select a number from 1 to 100?

Use random.randint(1, 100) when an integer with both endpoints included is required.

21. Hands-On Exercises

  1. Generate and print a random integer between 1 and 50.
  2. Generate ten floating-point values between 0 and 1.
  3. Simulate rolling a six-sided die twenty times.
  4. Generate random even numbers between 2 and 100.
  5. Choose one random name from a list of students.
  6. Select three distinct raffle winners from a list of participants.
  7. Shuffle a list of questions before presenting them to a user.
  8. Use choices() with weights to simulate outcomes with different probabilities.
  9. Use seed() to reproduce a short sequence of random values.
  10. Build a number guessing game with input validation.
  11. Create a random quiz application that chooses one question at a time.
  12. Compare a normal distribution with a uniform distribution using generated samples.

22. Quick Revision Checklist

  • import random imports the standard random module.
  • random.random() generates a float from 0.0 inclusive to 1.0 exclusive.
  • random.randint(a, b) includes both integer endpoints.
  • random.randrange() follows range-style stop and step rules.
  • random.uniform(a, b) generates a floating-point value over the specified interval.
  • random.choice() selects one item.
  • random.choices() selects with replacement.
  • random.sample() selects without replacement.
  • random.shuffle() modifies a mutable sequence in place.
  • random.seed() can make pseudorandom sequences reproducible.
  • The random module is not suitable for cryptographic security.
  • Use secrets for security-sensitive random values.

23. Conclusion

Python's random module provides a convenient set of tools for generating pseudorandom numbers, selecting values from sequences, shuffling lists, sampling populations, and simulating probability distributions.

Understanding the differences between randint(), randrange(), uniform(), choice(), choices(), sample(), and shuffle() helps you select the right tool for each task. By combining these functions with input validation, reproducible seeds, and clear function design, you can build reliable games, simulations, and testing utilities.

24. Additional Learning Resources

whatsapp