SoFunction
Updated on 2024-10-30

A simple demo of the python random library.

python random library simple use demo

When you need to generate random numbers or randomly select elements from a sequence, you can use Python's built-in random library. Here's an annotated example of how to use the random library:

# Import the random library
import random
# Generate a random decimal number between 0 and 1
random_float = ()
print(random_float)
# Generate a random integer within a specified range (including endpoints)
random_int = (1, 10)
print(random_int)
# Select a random element from the list
my_list = ["apple", "banana", "cherry"]
random_element = (my_list)
print(random_element)
# Disrupt the order of the list
my_list2 = ["apple", "banana", "cherry"]
(my_list2)
print(my_list2)
# Randomly select an element from a specified probability distribution (in this case a binomial distribution)
random_binomial = ([0, 1], weights=[0.7, 0.3])
print(random_binomial)
# Randomly select multiple elements from a specified sequence (here two elements are selected)
my_list3 = ["apple", "banana", "cherry", "date"]
random_sample = (my_list3, k=2)
print(random_sample)

The output may look like the following:

0.6253281864829788
5
banana
['banana', 'cherry', 'apple']
[1]
['banana', 'date']

The above code provides a common random operation, but this is not all, random library also provides a multitude of APIs, according to the needs of flexible use.

python random library simple to use demo's here, more information about python random library please pay attention to my other related articles!