Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Python Random Module

Last Updated on October 18, 2023 by Ankit Kochar

The Python programming language offers a wide range of modules and libraries to simplify various tasks. Among these, the random module in Python stands out as a powerful tool for generating random numbers, making decisions based on chance, and implementing various probabilistic algorithms. Whether you’re developing a game, conducting simulations, or adding randomness to your applications, the random module is an essential component of your Python toolkit.

In this article, we will dive into the world of the Python random module. We’ll explore its capabilities, functions, and how you can harness its power to introduce randomness into your Python programs. From generating random integers to shuffling lists and selecting random elements, this module offers a plethora of features that can enhance the versatility of your Python projects.

What is a Python Random Module?

Random module comes built-in with python which means that we do not need to install a package but just import and use it on the go. Python Random Module is useful in implementing a randomization algorithm. It can be used for generating integers from a specified range to pick the number from. Also, we have the feature to choose from a sequence of numbers of choice we can pick from a list of elements.

However, it generates the numbers in a pseudorandom manner that is not completely random if we deep dive further into its working mechanism under the hood but still remains effective for usage. Different functions from the Python Random Module are going to be discussed in this article with examples and explanations for each.

Seeding can be performed using seed() function where on seeding, the same value will be generated. It is used as a tool to initialize the value generator to reset in an algorithmic manner that once seeded, the sequence of values obtained remains the same.

Given below is an example of seeding in Python Random Module.

Example of Python Random Module:

import random

# Seed the random number generator
random.seed(2)

# Generate 4 random numbers
for i in range(4):
    print(random.random())
    random.seed(2)

Output:

0.9560342718892494
0.9560342718892494
0.9560342718892494
0.9560342718892494

Generating Random Numbers

Now that we have some idea about the python random module, we will be looking at how to generate numbers of different types using the methods of random library.

Float Value Between 0 and 1:-

In the below code mentioned, we can use the random() function to generate a float value between the range 0.0 and 1.0 such that value must me greater than or equal to 0.0 and strictly lesser than 1.0.

Syntax:

import random

# Generating random float
print(random.random())

Output:

0.23671507374354974

Integer Between Input Range:-

If we want to generate a random integer in a certain range then the randint() function proves to be the ideal that takes in two inputs, suppose a and b, and generates one between the two integers. It includes a and b as well in the result.

Syntax:

import random

#Generating Random integer
print(random.randint(1, 10))

Output:

4

Float Between Input Range:-

Similarly to generating integers between two input values, assumingly, a and b, we can generate a float value between the two inputs using uniform() function. The code below can be referred to for same.

Syntax:

import random

#Generating Random float
print(random.uniform(1, 10))

Output:

7.581086804968139

Working with Sequences

The application of the Python Random module is not limited to single values such as integer or float as we can use it to work on sequences as well.

Random K Elements From List (Without Replacing)

In case we have a list container and we want to pick only k values from it such that all of them are randomly picked without replacement, we can use sample(l,k) where l is the list container with elements and k is the number of required elements.

Syntax:

import random
items = [ 2, 3, 4, 5, 37, 8, 9, 10]
print(random.sample(items, 3))

Output:

[37, 9, 5]

Random K Elements From List (With Replacing Items)

In such a scenario where a sequence and k random values need to be picked, replacing the element then choice() function is the alternative to the sample() function where the same element can be picked multiple times. Give Python Random K elements from list code is given below:-

Syntax:

import random

items = [2, 3, 4, 25, 7, 38, 9]
print(random.choices(items, k=3))

Output:

[2, 3, 3]

Shuffling Sequences

To shuffle the list with random ordering, the shuffle() function can be used to perform the operation.

Syntax:

import random

# Shuffling Sequences
items = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10]
random.shuffle(items)
print(items)

Output:

[5, 8, 6, 11, 3, 10, 9, 4, 7, 2]

Generating Random Strings

The Python Random module is helpful in generating random strings of certain length provided as input by the user. The strings can be of different bases depending upon the function with code below where a hexadecimal string of length 10 is generated and 10 is encoded into base64 and a string value is returned.

Syntax:-

import random

# Generating Random Strings
print(random.hex(10))
print(random.b64encode(10))

Output:

'8b7c11d1f2'
b'Lp0RRmV7tg=='

Code – Password Generator Using Random Module

As we are done studying about the random module and what it can do with the function that it offers. Let us implement it in a real-world application by designing a password generator.

import random
import string

# Generating Random Passwords
def generatePassword(n):
    characters = string.ascii_letters + string.digits + string.punctuation
    password = ''.join(random.choices(characters, k=n))
    return password 

print("Enter the length of password you want to generate:-")
while True:
    password =  generatePassword(int(input()))
    print("Your password is: ",password)
    inp = input("Do you agree with password. Press Y or N - ")
    if inp == "Y":
        print("Password was changed!")
        break 

Output:

Enter if you want to generate password:-
Your password is:  vB%N&N[TG[eK6zF#Nl-@
Do you agree with password. Press Y or N - Y
Password was changed!

Explanation:
Password generator function takes an input that provides the length of password to be generated. It forms a string consisting of numbers, letters and punctuations such that the string is interpreted as the sequence to pick the random values from in it. choice() function is used giving the length of password to generate the password. As the prompt shows, if we want to go ahead with the password, we can go ahead or break out.

Conclusion
The random module in Python is a valuable resource for introducing randomness into your programs and projects. Whether you’re building games, conducting simulations, or need to make probabilistic decisions, this module provides a robust set of functions to help you achieve your goals. From generating random numbers with different distributions to shuffling sequences and selecting random elements, the "random" module’s capabilities are vast and versatile.

As you continue to explore Python’s random module, remember to consider the specific requirements of your project. Carefully select the appropriate randomization technique, distribution, or function to ensure that randomness serves its intended purpose effectively. With the "random" module in your programming arsenal, you can add unpredictability and excitement to your Python applications.

Frequently Asked Questions Related to Python Random Module

Here are some FAQs related to Python Random Module.

1. How do I generate a random integer in Python using the "random" module?
You can generate a random integer within a specified range using the randint() function. For example, random.randint(1, 10) generates a random integer between 1 and 10, inclusive.

2. Can I set the seed for the random number generator to make my results reproducible?
Yes, you can set the seed using the seed() function from the "random" module. Setting the seed ensures that you get the same sequence of random numbers in each run, which can be useful for debugging or creating reproducible results.

3. What’s the difference between random.random() and random.uniform(a, b) for generating random floating-point numbers?
Both functions generate random floating-point numbers between 0 and 1. The difference is that random.random() returns a number in the half-open interval [0, 1), while random.uniform(a, b) generates a random number in the closed interval [a, b].

4. How can I randomly shuffle a list in Python?
You can shuffle a list using the shuffle() function from the "random" module. For example, random.shuffle(my_list) will shuffle the elements of my_list in place.

5. What’s the difference between pseudo-random and truly random numbers in Python?
Python’s "random" module generates pseudo-random numbers, which are determined by an initial seed value. While they appear random for practical purposes, they are not truly random and can be reproduced if the seed is known. To achieve true randomness, you would need to use external hardware or sources of entropy.

Leave a Reply

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