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

  • Python Comments Tutorial: Single-line, Multi-line & Docstrings

    Comments in Python are lines of text within your code that are ignored by the Python interpreter. They are non-executable statements meant to provide explanations, documentation, or clarifications to yourself and other developers who might read your code. Types of Comments Uses of Comments Best Practices Example Python By using comments effectively, you can make…

  • Unlock the Power of Python: What is Python, History, Uses, & 7 Amazing Applications

    What is Python and History of python, different sectors python used Python is one of the most popular programming languages worldwide, known for its versatility and beginner-friendliness . From web development to data science and machine learning, Python has become an indispensable tool for developers and tech professionals across various industries . This blog post…

  • Raw Strings in Python

    Raw Strings in Python’s re Module Raw strings (prefixed with r) are highly recommended when working with regular expressions because they treat backslashes (\) as literal characters, preventing Python from interpreting them as escape sequences. path = ‘C:\Users\Documents’ pattern = r’C:\Users\Documents’ .4.1.1. Escape sequences Unless an ‘r’ or ‘R’ prefix is present, escape sequences in string and bytes literals are interpreted according…

  • pop(), remove(), clear(), and del 

    pop(), remove(), clear(), and del with 5 examples each, including slicing where applicable: 1. pop([index]) Removes and returns the item at the given index. If no index is given, it removes the last item. Examples: 2. remove(x) Removes the first occurrence of the specified value x. Raises ValueError if not found. Examples: 3. clear() Removes all elements from the list, making it empty. Examples: 4. del Statement Deletes elements by index or slice (not a method, but a…

  • File Handling in Python

    File Handling in Python File handling is a crucial aspect of programming that allows you to read from and write to files. Python provides built-in functions and methods to work with files efficiently. Basic File Operations 1. Opening a File Use the open() function to open a file. It returns a file object. python # Syntax: open(filename,…

  • Quantifiers (Repetition)

    Quantifiers (Repetition) in Python Regular Expressions – Detailed Explanation Basic Quantifiers 1. * – 0 or more occurrences (Greedy) Description: Matches the preceding element zero or more times Example 1: Match zero or more digits python import re text = “123 4567 89″ result = re.findall(r’\d*’, text) print(result) # [‘123’, ”, ‘4567’, ”, ’89’, ”] # Matches…

Leave a Reply

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