Back to Python
2025-12-275 min read

Random Module (Python Programming)

Learn Random Module (Python Programming) step by step with clear examples and exercises.

Title: Random Module (Python Programming)

Why This Matters

In programming, generating random numbers is essential for various applications such as simulations, cryptography, and game development. The Python random module provides a set of functions to generate random numbers, making it an indispensable tool in every Python programmer's arsenal. In this lesson, we will explore the usage of the random module, learn practical examples, and understand common mistakes that might arise during implementation.

Prerequisites

To fully grasp the concepts covered in this lesson, you should be familiar with:

  • Basic Python syntax and data structures (variables, functions, loops, etc.)
  • Understanding of basic mathematical operations
  • Familiarity with control flow statements like if, elif, and else

Core Concept

The random module in Python provides various functions for generating random numbers. Here are some key functions:

  1. random() - Returns a random float number between 0.0 and 1.0 (exclusive)
  2. randint(a, b) - Returns a random integer within the range from a to b (inclusive)
  3. choice(seq) - Returns a random element from the given sequence
  4. uniform(a, b) - Returns a random float number between a and b (inclusive)
  5. randrange(start, stop, step) - Returns a random integer within the specified range with a step size of step
  6. seed() - Sets the seed for the random number generator, allowing you to reproduce specific sequences of random numbers
  7. getstate() and setstate() - Used for saving and restoring the state of the random number generator

Working with Random Numbers

Let's explore some examples using the functions mentioned above:

import random

Generate a random float number between 0.0 and 1.0

random_float = random.random()

print(f"Random float: {random_float}")

Generate a random integer between 1 and 10 (inclusive)

random_integer = random.randint(1, 10)

print(f"Random integer: {random_integer}")

Generate a list of 5 random integers between 40 and 60 (inclusive)

random_list = [random.randrange(40, 61) for _ in range(5)]

print("Random list:", random_list)


### Generating Random Strings

The `choice()` function can also be used to generate random strings:

import string

import random

Generate a random string of length 10 using lowercase letters and digits

lowercase_letters = string.ascii_lowercase

digits = string.digits

random_string = ''.join(random.choice(lowercase_letters + digits) for _ in range(10))

print("Random string:", random_string)


### Generating Random Floats with Specific Precision

To generate a random float number with more than two decimal places, you can multiply the result by a suitable power of 10:

Generate a random float number with 5 decimal places

random_float = random.random() * (10 5) / 100000

print(f"Random float with 5 decimal places: {random_float}")

Worked Example

Let's create a simple game that generates a random number between 1 and 100, and asks the user to guess it. The program will provide feedback on whether the user’s guess is too high or too low:

import random

def game():
secret_number = random.randint(1, 100)
guess = None

while guess != secret_number:
guess = int(input("Guess a number between 1 and 100: "))

if guess < secret_number:
print("Too low! Try again.")
elif guess > secret_number:
print("Too high! Try again.")
else:
print("Congratulations! You found the secret number.")

game()

Common Mistakes

  1. Not importing the random module: Remember to include import random at the beginning of your script.
  2. Using the wrong function for the desired result: Make sure you use the appropriate function based on the task at hand (e.g., using random() instead of randint()).
  3. Not handling edge cases: Ensure that your code can handle invalid inputs, such as non-integer values or out-of-range numbers.
  4. Not seeding the random number generator: If you need to generate a sequence of random numbers in a specific order, use random.seed() to set a seed value.
  5. Generating too few or too many random numbers: Make sure that your code generates the correct number of random numbers based on the task requirements.
  6. Not using appropriate data structures for storing generated numbers: Ensure that you choose an appropriate data structure (e.g., list, set) for storing generated numbers when needed.

Practice Questions

  1. Write a function that generates 10 random integers between 50 and 70 (inclusive) and stores them in a list.
  2. Create a program that generates a random password consisting of uppercase letters, lowercase letters, digits, and special characters. The password should be 12 characters long.
  3. Write a function that returns the factorial of a given number using the random module (Hint: use recursion).
  4. Write a program that generates a list of random floating-point numbers with 5 decimal places between 0 and 1, and calculates their mean and standard deviation.
  5. Write a function that shuffles a list of items using the random module.

FAQ

  1. Why do we need to seed the random number generator?: Seeding allows us to generate specific sequences of random numbers, which can be useful for testing and debugging purposes.
  2. Can I generate a random float number with more than two decimal places using the random() function?: Yes, you can generate a random float number with more than two decimal places by multiplying the result by a suitable power of 10 (as shown in the lesson).
  3. Is it possible to generate random numbers using other Python modules?: Yes, there are other Python modules like numpy and scipy that offer more advanced random number generation capabilities, such as generating normal distributions or uniform distributions on higher-dimensional spaces. However, for basic random number generation, the random module is sufficient.
Random Module (Python Programming) | Python | XQA Learn