Random Module?

What is the Random Module?

The random module in Python is used to generate pseudo-random numbers. It’s perfect for:

  • Games
  • Simulations
  • Random sampling
  • Shuffling data
  • Generating test data

Random Module Methods with Examples

1. random() – Random float between 0.0 and 1.0

Generates a random floating-point number between 0.0 (inclusive) and 1.0 (exclusive).

python

import random

# Example 1: Basic random float
print(random.random())  # Output: 0.5488135079477204

# Example 2: Simulating probability (50% chance)
if random.random() < 0.5:
    print("Heads!")
else:
    print("Tails!")

# Example 3: Generating percentage-like values
percentage = random.random() * 100
print(f"Progress: {percentage:.2f}%")  # Output: Progress: 73.42%

2. uniform(1, 10) – Random float in specified range

Returns a random float between the specified range (inclusive of endpoints).

python

import random

# Example 1: Basic float in range
print(random.uniform(1, 10))  # Output: 6.423434

# Example 2: Temperature simulation
temperature = random.uniform(20.0, 35.5)
print(f"Current temperature: {temperature:.1f}°C")  # Output: Current temperature: 28.7°C

# Example 3: Price range
price = random.uniform(99.99, 199.99)
print(f"Product price: ${price:.2f}")  # Output: Product price: $156.75

3. randint(1, 100) – Random integer in range

Returns a random integer between the specified range (inclusive of both endpoints).

python

import random

# Example 1: Basic random integer
print(random.randint(1, 100))  # Output: 57

# Example 2: Dice roller (six-sided die)
dice_roll = random.randint(1, 6)
print(f"Dice roll: {dice_roll}")  # Output: Dice roll: 4

# Example 3: Age generator
age = random.randint(18, 65)
print(f"Random age: {age} years")  # Output: Random age: 34 years

4. randrange(1, 10, 2) – Random with step control

Returns a randomly selected element from a range with specified step.

python

import random

# Example 1: Odd numbers between 1-10
print(random.randrange(1, 10, 2))  # Output: 7 (from 1,3,5,7,9)

# Example 2: Even numbers between 0-20
even_num = random.randrange(0, 21, 2)
print(f"Even number: {even_num}")  # Output: Even number: 14

# Example 3: Multiples of 5 between 5-50
multiple_of_5 = random.randrange(5, 51, 5)
print(f"Multiple of 5: {multiple_of_5}")  # Output: Multiple of 5: 35

5. choice(list) – Random element from sequence

Returns a random element from a non-empty sequence.

python

import random

# Example 1: Random name from list
names = ["Alice", "Bob", "Charlie", "Diana"]
print(random.choice(names))  # Output: Charlie

# Example 2: Random weekday
weekdays = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
print(f"Random day: {random.choice(weekdays)}")  # Output: Random day: Wed

# Example 3: Rock, Paper, Scissors
choices = ["Rock", "Paper", "Scissors"]
computer_choice = random.choice(choices)
print(f"Computer chose: {computer_choice}")  # Output: Computer chose: Paper

6. choices(list, k=2) – Multiple random elements

Returns multiple random elements from a sequence (with replacement).

python

import random

# Example 1: Multiple names
names = ["Alice", "Bob", "Charlie", "Diana"]
print(random.choices(names, k=2))  # Output: ['Bob', 'Alice']

# Example 2: Lottery numbers (can have duplicates)
lottery = random.choices(range(1, 51), k=6)
print(f"Lottery numbers: {lottery}")  # Output: Lottery numbers: [12, 45, 12, 33, 7, 28]

# Example 3: Random team selection
players = ["Player1", "Player2", "Player3", "Player4"]
team = random.choices(players, k=2)
print(f"Team members: {team}")  # Output: Team members: ['Player3', 'Player1']

7. shuffle(list) – Shuffle sequence in-place

Randomizes the order of elements in a list (modifies the original list).

python

import random

# Example 1: Shuffle a list of numbers
numbers = [1, 2, 3, 4, 5]
random.shuffle(numbers)
print(numbers)  # Output: [3, 1, 5, 2, 4]

# Example 2: Shuffle a deck of cards
cards = ["Ace", "King", "Queen", "Jack", "10"]
random.shuffle(cards)
print(f"Shuffled deck: {cards}")  # Output: Shuffled deck: ['Jack', 'Ace', '10', 'Queen', 'King']

# Example 3: Shuffle quiz questions
questions = ["Q1", "Q2", "Q3", "Q4", "Q5"]
random.shuffle(questions)
print(f"Quiz order: {questions}")  # Output: Quiz order: ['Q4', 'Q1', 'Q3', 'Q5', 'Q2']

8. seed(10) – Initialize random generator

Sets the seed value for reproducible random sequences.

python

import random

# Example 1: Reproducible random numbers
random.seed(10)
print(random.random())  # Always: 0.5714025946899135
print(random.random())  # Always: 0.4288890546751146

# Example 2: Same seed = same results
random.seed(42)
result1 = [random.randint(1, 10) for _ in range(3)]
random.seed(42)
result2 = [random.randint(1, 10) for _ in range(3)]
print(f"Result 1: {result1}")  # Output: Result 1: [2, 1, 5]
print(f"Result 2: {result2}")  # Output: Result 2: [2, 1, 5] (same!)

# Example 3: Testing with fixed seed
random.seed(123)
test_data = [random.uniform(0, 1) for _ in range(3)]
print(f"Test data: {test_data}")  # Always same for testing

9. getstate() / setstate() – Save/restore random state

Saves and restores the internal state of the random number generator.

python

import random

# Example 1: Save and restore state
print("First number:", random.randint(1, 100))  # Output: First number: 45

# Save current state
state = random.getstate()

print("Second number:", random.randint(1, 100))  # Output: Second number: 78
print("Third number:", random.randint(1, 100))   # Output: Third number: 23

# Restore to saved state
random.setstate(state)

print("After restore:", random.randint(1, 100))  # Output: After restore: 78 (same as second)
print("Next number:", random.randint(1, 100))    # Output: Next number: 23 (same as third)

# Example 2: Continue from saved point
random.seed(100)
print(random.random())  # Output: 0.1456692551041303

saved_state = random.getstate()
print(random.random())  # Output: 0.45492700451402135

random.setstate(saved_state)
print(random.random())  # Output: 0.45492700451402135 (same as above)

# Example 3: Multiple save points
state1 = random.getstate()
num1 = random.randint(1, 10)
state2 = random.getstate()
num2 = random.randint(1, 10)

random.setstate(state1)
print(f"From state1: {random.randint(1, 10)}")  # Same as num1
random.setstate(state2)
print(f"From state2: {random.randint(1, 10)}")  # Same as num2

10. getrandbits(3) – Random number by bit count

Generates a random number with the specified number of bits.

python

import random

# Example 1: 3 bits (0-7 range)
print(random.getrandbits(3))  # Output: 5 (binary: 101)

# Example 2: Different bit sizes
print(f"4 bits: {random.getrandbits(4)}")   # Range: 0-15
print(f"8 bits: {random.getrandbits(8)}")   # Range: 0-255
print(f"16 bits: {random.getrandbits(16)}") # Range: 0-65535

# Example 3: Generating binary numbers
bits_3 = random.getrandbits(3)
bits_5 = random.getrandbits(5)
print(f"3-bit number: {bits_3} (binary: {bin(bits_3)})")
print(f"5-bit number: {bits_5} (binary: {bin(bits_5)})")
# Output: 3-bit number: 3 (binary: 0b11)
# Output: 5-bit number: 17 (binary: 0b10001)

📊 Quick Reference

MethodPurposeRange/Output
random()Random float0.0 to 1.0
uniform(a,b)Float in rangea to b
randint(a,b)Integer in rangea to b (inclusive)
randrange(s,e,step)Integer with steps to e with step
choice(seq)One random elementFrom sequence
choices(seq,k)Multiple elementsList of k elements
shuffle(list)Reorder listModifies original
seed(n)Set starting pointReproducible results
getstate()/setstate()Save/restoreContinue sequence
getrandbits(k)Random by bits0 to 2^k-1

Similar Posts

  • Create lists

    In Python, there are multiple ways to create lists, depending on the use case. Below are the most common methods: 1. Direct Initialization (Using Square Brackets []) The simplest way to create a list is by enclosing elements in square brackets []. Example: python empty_list = [] numbers = [1, 2, 3, 4] mixed_list = [1, “hello”, 3.14,…

  • Closure Functions in Python

    Closure Functions in Python A closure is a function that remembers values from its enclosing lexical scope even when the program flow is no longer in that scope. Simple Example python def outer_function(x): # This is the enclosing scope def inner_function(y): # inner_function can access ‘x’ from outer_function’s scope return x + y return inner_function…

  • The Fractions module

    The Fractions module in Python is a built-in module that provides support for rational number arithmetic. It allows you to work with fractions (like 1/2, 3/4, etc.) exactly, without the precision issues that can occur with floating-point numbers. What Problems Does It Solve? Problem with Floating-Point Numbers: python # Floating-point precision issue print(0.1 + 0.2) # Output:…

  • Python Calendar Module

    Python Calendar Module The calendar module in Python provides functions for working with calendars, including generating calendar data for specific months or years, determining weekdays, and performing various calendar-related operations. Importing the Module python import calendar Key Methods in the Calendar Module 1. calendar.month(year, month, w=2, l=1) Returns a multiline string with a calendar for the specified month….

  • Python Exception Handling – Basic Examples

    1. Basic try-except Block python # Basic exception handlingtry: num = int(input(“Enter a number: “)) result = 10 / num print(f”Result: {result}”)except: print(“Something went wrong!”) Example 1: Division with Zero Handling python # Handling division by zero error try: num1 = int(input(“Enter first number: “)) num2 = int(input(“Enter second number: “)) result = num1 /…

Leave a Reply

Your email address will not be published. Required fields are marked *