Back to Python
2026-02-228 min read

Random Number Generator (Python Programming)

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

Title: Random Number Generator (Python Programming)

Why This Matters

In programming, generating random numbers is a fundamental concept that has various applications such as game development, simulations, cryptography, and statistical analysis. Python's built-in random module simplifies the process of creating random numbers, making it an essential skill for every programmer. This lesson will delve deeper into the core concepts, worked examples, common mistakes, practice questions, and frequently asked questions related to generating random numbers in Python.

Prerequisites

Before diving into the random number generator, familiarize yourself with the following prerequisites:

  1. Basic understanding of Python syntax and variables
  2. Familiarity with data types like integers, floats, and strings
  3. Knowledge of control structures such as loops and conditional statements
  4. Understanding of functions and modules in Python
  5. Experience with list comprehensions and sets
  6. Comfortable working with the Python interactive shell (REPL)
  7. Basic understanding of probability concepts like distributions, mean, median, and standard deviation
  8. Familiarity with mathematical operations involving random variables

Core Concept

The random module in Python provides various functions to generate random numbers based on different distributions. Here are some key functions:

  1. random() – Returns a random float number between 0.0 and 1.0 (exclusive). This function can be used to generate random numbers for any range by multiplying the result with the desired upper limit and adding the lower limit. For example, to generate a random number between 1 and 100:
import random
random_number = int(random.random() * 100) + 1
print(random_number)
  1. randint(a, b) – Returns a random integer within the range a to b-1. This function is useful when you need exact integer values within a specific range. For example, to generate 10 random integers between 1 and 100:
import random
numbers = [random.randint(1, 100) for _ in range(10)]
print(numbers)
  1. choice(seq) – Returns a random element from the non-empty sequence seq. This function is handy when you need to select an item randomly from a list or other iterable object. For example, to choose a random card from a deck of 52 cards:
import random
deck = [f"{suit} {rank}" for suit in "Spades Hearts Diamonds Clubs" for rank in "Ace 2 3 4 5 6 7 8 9 10 Jack Queen King".split()]
random_card = random.choice(deck)
print(random_card)
  1. seed() – Sets the seed for the random number generator. A seed is an initial value that determines the sequence of random numbers generated by the algorithm. By setting a seed, you can generate the same sequence of random numbers for debugging or testing purposes. For example:
import random
random.seed(42) # Set the seed to 42
for _ in range(10):
print(random.randint(1, 10)) # The output will always be the same sequence of 10 numbers between 1 and 10
  1. uniform(a, b) – Returns a random float number uniformly distributed between a (inclusive) and b (exclusive). For example:
import random
random_number = random.uniform(1, 100)
print(random_number)
  1. gauss(mu=0, sigma=1) – Returns a random float number following the standard normal distribution with mean mu and standard deviation sigma. For example:
import random
random_number = random.gauss(50, 20)
print(random_number)
  1. normalvariate(mu=0, sigma=1) – Returns a random float number following the normal distribution with mean mu and standard deviation sigma. This function is more accurate than gauss() for generating numbers from the normal distribution. For example:
import random
random_number = random.normalvariate(50, 20)
print(random_number)
  1. randrange(start=None, stop=None, step=1) – Returns a sequence of random integers within the range defined by start, stop, and step. For example:
import random
numbers = random.randrange(0, 20, 3)
print(numbers)
  1. sample(population, length) – Returns a list of length random elements from the non-empty sequence population. For example:
import random
numbers = random.sample([1, 2, 3, 4, 5, 6, 7, 8, 9], 3)
print(numbers)

Worked Example

Let's create a simple program to generate a random password consisting of 8 characters—4 uppercase letters, 3 digits, and 1 special character chosen from !@#$%^&*()-_+=. First, we'll use the string module for generating the required character sets:

import string
import random

uppercase = string.ascii_uppercase
lowercase = string.ascii_lowercase
digits = string.digits
special_chars = "!@#$%^&*()-_+="

password_characters = uppercase + lowercase + digits + special_chars
password = ''.join(random.choice(password_characters) for _ in range(8))
print(password)

In this example, we first import the string module and then define four character sets: uppercase letters, lowercase letters, digits, and special characters. We combine these sets into a single list called password_characters. Then, we use a list comprehension to generate an 8-character password by choosing a random character from each set.

Common Mistakes

  1. Not importing the random module: Always remember to import the random module at the beginning of your script.
  2. Using the wrong function for the desired output: Make sure you use the appropriate function based on your requirements (e.g., using random() instead of randint(a, b)).
  3. Not setting a seed: If you want to generate the same sequence of random numbers for debugging or testing purposes, set a seed value using random.seed(seed_value).
  4. Forgetting to close the random module: Always remember to close the random module with import random at the end of your script if it's not being used anymore.
  5. Not handling the case when generating a random element from an empty sequence: When using the choice() function, ensure that the provided sequence is non-empty to avoid errors or unexpected behavior.
  6. Generating too many random numbers: Be mindful of the number of random numbers you need and generate only as many as required to reduce computational overhead.
  7. Not understanding the distribution of generated numbers: Understand the distribution of the generated numbers by using appropriate functions like uniform(), gauss(), or normalvariate().
  8. Not considering edge cases in range definition: Be aware of edge cases when defining ranges, such as including or excluding the endpoints and ensuring that step values are not zero.
  9. Using non-integer steps in randrange(): When using randrange(), ensure that the step value is an integer to avoid errors.
  10. Not considering the impact of seed on random number generation: Understand how setting a seed affects the sequence of generated numbers and use it accordingly for debugging or testing purposes.

Practice Questions

  1. Write a Python program that generates 20 random floating-point numbers between 0 and 1 (inclusive) using the random() function.
import random
for _ in range(20):
print(random.random())
  1. Modify the worked example to generate 5 random integers between 50 and 200.
import random

upper_limit = 200
lower_limit = 50
numbers = [random.randint(lower_limit, upper_limit) for _ in range(5)]
print(numbers)
  1. Write a Python program that generates a random password consisting of 8 characters—4 uppercase letters, 3 digits, and 1 special character chosen from !@#$%^&*()-_+=.

(Answer provided in the Worked Example section)

  1. Write a Python program that generates 10 random floating-point numbers following the standard normal distribution with mean 50 and standard deviation 20 using the gauss() function.
import random
for _ in range(10):
print(random.gauss(50, 20))
  1. Write a Python program that generates a list of 10 random integers between 1 and 100 using the randrange() function with a step of 3.
import random
numbers = [random.randrange(1, 101, 3) for _ in range(10)]
print(numbers)
  1. Write a Python program that generates a list of 5 random elements from the set {1, 2, 3, 4, 5, 6, 7, 8, 9}.
import random
numbers = random.sample({1, 2, 3, 4, 5, 6, 7, 8, 9}, 5)
print(numbers)

FAQ

  1. Why does my program generate the same sequence of random numbers every time I run it?
  • This could be because you forgot to set a seed value for the random number generator, or you're using the same seed value each time. To generate different sequences, either don't set a seed or use a different seed value each time.
  1. How can I ensure that my program generates unique random numbers within a specific range without repetition?
  • You can store generated numbers in a set to ensure uniqueness and then replace the set with a list before printing. Alternatively, you can generate a larger number of random numbers than needed and remove duplicates using a loop or a library like collections.Counter.
  1. What happens if I don't close the random module at the end of my script?
  • Leaving the random module open may lead to unexpected behavior in your program or other scripts that use the same module, as it maintains its state between runs. Always remember to close the module when it's no longer needed.
  1. Is there a way to generate random numbers with a specific distribution?
  • Yes, Python provides additional modules like numpy and scipy that offer functions for generating random numbers following various distributions such as normal, uniform, exponential, and more. These can be useful in statistical analysis and machine learning applications.
  1. Can I use the random module to generate random strings?
  • Yes, you can generate random strings using the random() function along with string concatenation or list comprehension. For example:
import random
import string

length = 10
random_string = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(length))
print(random_string)
  1. How can I generate a random permutation of a list using the random module?
  • You can use the random.shuffle() function to randomly shuffle a list and then access its elements to create a new list. For example:
import random

original_list = [1, 2, 3, 4, 5]
random.shuffle(original_list)
print(original_list)
  1. How can I generate a random sample with replacement from a list using the random module?
  • You can use the random.choices() function to randomly select elements from a list with or without replacement. For example:
import random

original_list = [1, 2, 3, 4, 5]
sample = random.choices(original_list, k=5)
print(sample)
  1. How can I generate a random subset of a list using the random module?
  • You can use the random.sample() function to randomly select a specified number of elements from a list without replacement. For example:
import random

original_list = [1, 2, 3, 4, 5]
subset = random.sample(original_list, 3)
print(subset)
Random Number Generator (Python Programming) | Python | XQA Learn