Random Module?

UpComing SoftWare Training Demos

πŸš€ *Gen AI EngineerΒ Telugu (Production Focused)*
πŸ—“οΈ *Date:* 30th Sept 2026, 07:00AM IST
πŸ“ *Register Now!:*
https://www.vlrt.in/gr
πŸ‘₯ *Join WA Community:*
https://www.vlrt.in/gw
πŸ’‘*Course Content:*
https://www.vlrt.in/ai
▢️ *Demo Videos:*
https://www.vlrt.in/gv

πŸš€ *Service now Admin/ Development (ITSM)FREE Demo in Telugu*
πŸ—“οΈ *Date:* 30th Sept 2026, 08:00AM IST
πŸ“ *Register Now!:*
https://www.vlrt.in/7r
πŸ‘₯ *Join WA Community:*
https://www.vlrt.in/7w
πŸ’‘*Course Content:*
https://www.vlrt.in/7c
▢️ *Demo Videos:*
https://www.vlrt.in/7v

πŸš€ *Vulnerability Management Training Demo*
πŸ—“οΈ *Date:* 30th Sept 2026, 09:00 AM IST
πŸ“*Register Now!:*
https://www.vlrt.in/vr
πŸ‘₯ *Join Community:*
https://www.vlrt.in/cw
πŸ’‘ *Course Content:*
https://www.vlrt.in/vc
▢️ *Demo Videos:*
https://www.vlrt.in/Vm

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

  • Negative lookbehind assertion

    A negative lookbehind assertion in Python’s re module is a zero-width assertion that checks if a pattern is not present immediately before the current position. It is written as (?<!…). It’s the opposite of a positive lookbehind and allows you to exclude matches based on what precedes them. Similar to the positive lookbehind, the pattern…

  • Iterators in Python

    Iterators in Python An iterator in Python is an object that is used to iterate over iterable objects like lists, tuples, dictionaries, and sets. An iterator can be thought of as a pointer to a container’s elements. To create an iterator, you use the iter() function. To get the next element from the iterator, you…

  • Tuples

    In Python, a tuple is an ordered, immutable (unchangeable) collection of elements. Tuples are similar to lists, but unlike lists, they cannot be modified after creation (no adding, removing, or changing elements). Key Features of Tuples: Syntax: Tuples are defined using parentheses () (or without any brackets in some cases). python my_tuple = (1, 2, 3, “hello”) or (without…

  • recursive function

    A recursive function is a function that calls itself to solve a problem. It works by breaking down a larger problem into smaller, identical subproblems until it reaches a base case, which is a condition that stops the recursion and provides a solution to the simplest subproblem. The two main components of a recursive function…

  • Predefined Character Classes

    Predefined Character Classes Pattern Description Equivalent . Matches any character except newline \d Matches any digit [0-9] \D Matches any non-digit [^0-9] \w Matches any word character [a-zA-Z0-9_] \W Matches any non-word character [^a-zA-Z0-9_] \s Matches any whitespace character [ \t\n\r\f\v] \S Matches any non-whitespace character [^ \t\n\r\f\v] 1. Literal Character a Matches: The exact character…

  • (?),Greedy vs. Non-Greedy, Backslash () ,Square Brackets [] Metacharacters

    The Question Mark (?) in Python Regex The question mark ? in Python’s regular expressions has two main uses: 1. Making a Character or Group Optional (0 or 1 occurrence) This is the most common use – it makes the preceding character or group optional. Examples: Example 1: Optional ‘s’ for plural words python import re pattern…

Leave a Reply

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