Python Random Module: Usage & Examples

The random function is a module in the Python standard library that can be used to generate pseudo-random numbers. It offers a variety of functions for generating random numbers and manipulating them.

Here are the usages of several commonly used functions in the random module:

  1. Generate a random float number between 0 and 1 using random.random().
import random

num = random.random()
print(num)
  1. random.randint(a, b): generates a random integer between a and b, inclusive of both.
import random

num = random.randint(1, 100)
print(num)
  1. randomly select an element from the sequence
import random

choices = ['apple', 'banana', 'orange']
fruit = random.choice(choices)
print(fruit)
  1. Shuffle the elements in the sequence randomly using random.shuffle(sequence).
import random

numbers = [1, 2, 3, 4, 5]
random.shuffle(numbers)
print(numbers)
  1. randomly select k elements from the sequence and return a new list.
import random

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

These are just a small subset of the functions provided by the random module; there are many more functions available for generating different types of random numbers.

bannerAds