Python ModulesRandom Tutorial

RANDOM MODULE

Python has a built-in module called random that you can use to generate random numbers. It is useful for scenarios like:

  • Getting a random number.
  • Generating random passwords.
  • Selecting random elements from a list.
  • Shuffling elements randomly.
  • Deciding elements to appear in a random order.

Using the Random Module

To use the random module, first import it:

import random

Commonly Used Functions in the Random Module

FunctionDescription
random()Returns a random float number between 0 and 1.
randrange(a, b)Returns a random number between the given range [a, b).
randint(a, b)Returns a random integer between a and b (inclusive).
seed()Initializes the random number generator.
shuffle()Randomly rearranges the elements in a list.
choice()Selects a random element from a sequence.

Examples

Example 1: Display 2 Random Numbers Using random()

# Example 1
import random
 
# Generate two random float numbers
print(random.random())  # Output: Random float between 0 and 1
print(random.random())  # Output: Random float between 0 and 1

Example 2: Display a Random Number in a User-Defined Range

# Example 2
import random
 
# Generate a random number between 1 and 100
print(random.randint(1, 100))  # Output: Random integer between 1 and 100

Example 3: Shuffle a List Using random.shuffle()

# Example 3
import random
 
# Define a list of items
items = [1, 2, 3, 4, 5]
 
# Shuffle the list
random.shuffle(items)
print(items)  # Output: A randomly shuffled list

Example 4: Pick a Random Element Using random.choice()

# Example 4
import random
 
# Define a list of fruits
fruits = ['Apple', 'Banana', 'Mango', 'Grapes', 'Orange']
 
# Pick a random fruit
print(random.choice(fruits))  # Output: A randomly selected fruit

Try It Yourself

Problem 1: Generate Random Numbers

Generate 5 random numbers between 1 and 10.

Show Code
import random
 
# Generate 5 random numbers between 1 and 10
for _ in range(5):
    print(random.randint(1, 10))

Problem 2: Assign Random Fruits to Days

Take two lists: one for weekdays (Monday to Friday) and another for 5 fruits. Assign a random fruit to each weekday.

Show Code
import random
 
# Lists for days and fruits
days = ['Mon', 'Tue', 'Wed', 'Thurs', 'Fri']
fruits = ['Apple', 'Guava', 'Grapes', 'Banana', 'Mango']
 
# Assign a random fruit to each day
for day in days:
    print(f"{day} = {random.choice(fruits)}")

Pyground

Play with Python!

Output: