how to use the Python random library to generate random numbers

Published on Aug. 22, 2023, 12:15 p.m.

Sure, here’s an example of how to use the Python random library to generate random numbers:

import random

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

# Generate a random float between 0 and 1
flt = random.random()
print(flt)

# Shuffle a list
my_list = [1, 2, 3, 4, 5]
random.shuffle(my_list)
print(my_list)

In this example, we use the random.randint() method to generate a random integer between 1 and 10 (inclusive), the random.random() method to generate a random float between 0 and 1, and the random.shuffle() method to shuffle a list.

There are many more methods available in the Python random library for generating random numbers and manipulating random values, such as selecting a random item from a list, generating random strings, and more. You can explore the Python documentation to learn more about the random library and its functionalities.

Tags: