How to generate a random number in Python? (5 examples)

A random number is a value chosen from a set of possible values in a seemingly unpredictable manner. In computing and mathematics, random numbers are essential in various applications, simulations, cryptography, and more.

True randomness is difficult to achieve, especially in computers, which are deterministic machines. Computers usually generate what are known as pseudorandom numbers. Pseudorandom numbers are generated by algorithms that use an initial value called a seed. Given the same seed, the algorithm will produce the same sequence of numbers. However, the sequence can appear random enough for many practical purposes with an excellent pseudorandom number generator.

You can use the random module from the Python standard library to generate random numbers in Python.

Here are a few examples of how to generate random numbers using the random module:

  1. Generate a random integer within a specific range:
import random

# Generate a random integer between 1 and 10 (inclusive)
random_integer = random.randint(1, 10)
print(random_integer)
  1. Generate a random floating-point number between 0 and 1:
import random

# Generate a random floating-point number between 0 and 1
random_float = random.random()
print(random_float)
  1. Generate a random floating-point number within a specified range:
import random

# Generate a random floating-point number between 0 and 10
random_float_range = random.uniform(0, 10)
print(random_float_range)
  1. Generate a random element from a sequence (list, tuple, string, etc.):
import random

my_list = [1, 2, 3, 4, 5]

# Choose a random element from the list
random_element = random.choice(my_list)
print(random_element)
  1. Shuffle a sequence in random order:
import random

my_list = [1, 2, 3, 4, 5]

# Shuffle the list in-place
random.shuffle(my_list)
print(my_list)

Remember that the random module generates pseudorandom numbers, which means an initial seed value determines the sequence of numbers generated. If you want to generate different sequences of random numbers in different program runs, you can set a different seed using the random.seed() function. If you don’t set a seed explicitly, the random number generator is typically seeded based on the system time.

For cryptographic applications, it’s recommended to use the secrets module, which provides functions for generating cryptographically secure random numbers and tokens.