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

  • Functions as Parameters in Python

    Functions as Parameters in Python In Python, functions are first-class objects, which means they can be: Basic Concept When we pass a function as a parameter, we’re essentially allowing one function to use another function’s behavior. Simple Examples Example 1: Basic Function as Parameter python def greet(name): return f”Hello, {name}!” def farewell(name): return f”Goodbye, {name}!” def…

  • What is list

    In Python, a list is a built-in data structure that represents an ordered, mutable (changeable), and heterogeneous (can contain different data types) collection of elements. Lists are one of the most commonly used data structures in Python due to their flexibility and dynamic nature. Definition of a List in Python: Example: python my_list = [1, “hello”, 3.14,…

  • Python Nested Lists

    Python Nested Lists: Explanation & Examples A nested list is a list that contains other lists as its elements. They are commonly used to represent matrices, tables, or hierarchical data structures. 1. Basic Nested List Creation python # A simple 2D list (matrix) matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9]…

  • Global And Local Variables

    Global Variables In Python, a global variable is a variable that is accessible throughout the entire program. It is defined outside of any function or class. This means its scope is the entire file, and any function can access and modify its value. You can use the global keyword inside a function to modify a…

  • positive lookahead assertion

    A positive lookahead assertion in Python’s re module is a zero-width assertion that checks if the pattern that follows it is present, without including that pattern in the overall match. It is written as (?=…). The key is that it’s a “lookahead”—the regex engine looks ahead in the string to see if the pattern inside…

Leave a Reply

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