Ticker

6/recent/ticker-posts

Random Module in Python

Random Module in Python

Introduction: 

The random module in Python provides functions to generate random numbers and perform random operations. It is commonly used for tasks such as generating random integers, selecting random elements from a list, shuffling data, and more.

Importing the Random Module:
To use the random module, you need to import it first. You can do this using the following code:

python
import random

Generating Random Integers:
The random module allows you to generate random integers within a specified range using the randint() function. The function takes two arguments: the lower bound and the upper bound of the range (both inclusive).

python
import random

# Generate a random integer between 1 and 10
random_integer = random.randint(1, 10)
print(random_integer)

Generating Random Floating-Point Numbers:
To generate random floating-point numbers between 0 and 1, you can use the random() function.

python
import random

# Generate a random floating-point number between 0 and 1
random_float = random.random()
print(random_float)

Selecting Random Elements from a List:
The random module provides a function called choice() that allows you to select a random element from a list.

python
import random

fruits = ['apple', 'banana', 'orange', 'grape', 'kiwi']

# Select a random fruit from the list
random_fruit = random.choice(fruits)
print(random_fruit)

Shuffling a List:
You can use the shuffle() function to randomly shuffle the elements of a list.

python
import random

numbers = [1, 2, 3, 4, 5]

# Shuffle the list randomly
random.shuffle(numbers)
print(numbers)

Randomly Sampling from a List:
The sample() function allows you to extract a random sample of elements from a list without replacement.

python
import random

cards = ['ace', 'king', 'queen', 'jack', '10', '9', '8', '7']

# Get a random sample of 3 cards from the list
random_sample = random.sample(cards, 3)
print(random_sample)

Setting a Random Seed:
If you want to generate the same set of random numbers in different executions of the program, you can set a random seed using the seed() function.

python
import random

# Set the random seed to 42
random.seed(42)

# Generate random integers using the same seed
random_int1 = random.randint(1, 100)
random_int2 = random.randint(1, 100)

print(random_int1, random_int2) # These values will be the same in each execution

Conclusion:
The random module in Python is a powerful tool for generating randomness in your programs. By using its functions like randint(), random(), choice(), shuffle(), and sample(), you can perform various random operations to suit your application's needs.

Post a Comment

0 Comments