Write python's random module

randomis a module built into Python that provides functions and methods for generating random numbers. randomFunctions such as generating random numbers, shuffling sequences, and randomly selecting elements can be realized by using modules.

The following are randomsome commonly used functions and methods in the module:

  1. random.random(): Generate a random floating point number between 0 and 1.

  2. random.randint(a, b): Generate a random integer between a and b, including a and b.

  3. random.choice(seq): Randomly select an element from the sequence seq.

  4. random.shuffle(seq): Randomly shuffle the elements in the sequence seq.

  5. random.sample(population, k): Randomly select k elements from the population and return a new list.

  6. random.uniform(a, b): Generate a random floating-point number between a and b, including a and b.

Here is some randomsample code using the module:

import random

# 生成一个0到1之间的随机浮点数
print(random.random())

# 生成一个1到10之间的随机整数
print(random.randint(1, 10))

# 从列表中随机选择一个元素
my_list = [1, 2, 3, 4, 5]
print(random.choice(my_list))

# 将列表中的元素随机打乱
random.shuffle(my_list)
print(my_list)

# 从列表中随机选择3个元素
print(random.sample(my_list, 3))

# 生成一个1到5之间的随机浮点数
print(random.uniform(1, 5))

It should be noted that randomthe random numbers generated by the module are pseudo-random numbers, that is, they are generated according to a specific algorithm, not truly random. Therefore, in some cases, other more sophisticated methods may need to be used if highly secure randomness is required.

Guess you like

Origin blog.csdn.net/qq_44370158/article/details/131654382