Random Module?

UpComing SoftWare Training Demos

🚀 *Playwright With AI Testing Demo In Telugu*
🗓️ *Date:* 28 Oct2026, 08:00 PM IST
📝 *Register Now!:*
https://www.vlrt.in/3r
👥 *Join WA Community:*
https://www.vlrt.in/3w
💡 *Course Content:*
https://www.vlrt.in/3c
▶️ *Demo Videos:*
https://www.vlrt.in/3v

🚀 *Gen AI Engineer (Production Focused)*
🗓️ *Date:* 29th Oct 2026, 06:00PM 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

🚀 *Vulnerability Management Training Demo*
🗓️ *Date:* 28th Oct 2026, 10: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

  • Formatted printing

    C-Style String Formatting in Python Python supports C-style string formatting using the % operator, which provides similar functionality to C’s printf() function. This method is sometimes called “old-style” string formatting but remains useful in many scenarios. Basic Syntax python “format string” % (values) Control Characters (Format Specifiers) Format Specifier Description Example Output %s String “%s” % “hello” hello %d…

  • Static Methods

    The primary use of a static method in Python classes is to define a function that logically belongs to the class but doesn’t need access to the instance’s data (like self) or the class’s state (like cls). They are essentially regular functions that are grouped within a class namespace. Key Characteristics and Use Cases General…

  • How to Use Python’s Print Function and Avoid Syntax and Indentation Errors

    1. Print Output to Console and String Manipulation Tips for the print() Function What is the print() Function? The print() function in Python is used to display output to the console. It is one of the most commonly used functions, especially for debugging and displaying results. Basic Usage Output: String Manipulation Tips for print() 1….

  • Combined Character Classes

    Combined Character Classes Explained with Examples 1. [a-zA-Z0-9_] – Word characters (same as \w) Description: Matches any letter (lowercase or uppercase), any digit, or underscore Example 1: Extract all word characters from text python import re text = “User_name123! Email: test@example.com” result = re.findall(r'[a-zA-Z0-9_]’, text) print(result) # [‘U’, ‘s’, ‘e’, ‘r’, ‘_’, ‘n’, ‘a’, ‘m’, ‘e’, ‘1’, ‘2’,…

  • Linear vs. Scalar,Homogeneous vs. Heterogeneous 

    Linear vs. Scalar Data Types in Python In programming, data types can be categorized based on how they store and organize data. Two important classifications are scalar (atomic) types and linear (compound) types. 1. Scalar (Atomic) Data Types 2. Linear (Compound/Sequential) Data Types Key Differences Between Scalar and Linear Data Types Feature Scalar (Atomic) Linear (Compound) Stores Single…

  • non-capturing group, Named Groups,groupdict()

    To create a non-capturing group in Python’s re module, you use the syntax (?:…). This groups a part of a regular expression together without creating a backreference for that group. A capturing group (…) saves the matched text. You can then access this captured text using methods like group(1), group(2), etc. A non-capturing group (?:…)…

Leave a Reply

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