Common functions/methods of random modules in Python (2)-random.random(), random.randint() and random.uniform()

1. random.random(): Generate a random number of points from 0 to 1: 0 <= n <1.0

Syntax: random.random()

#生成一个0~1之间的随机浮点数
print("生成一个0~1之间的随机浮点数(1):",random.random())
print("生成一个0~1之间的随机浮点数(2):",random.random())
random.seed(1)
print("生成一个0~1之间的随机浮点数(3):",random.random())
random.seed(1)
print("生成一个0~1之间的随机浮点数(4):",random.random())

Insert picture description here
Through the above example, it can be found that without setting the seed number, random.random() will randomly generate a floating point number between 0 and 1. (Readers who have doubts about the number of seeds can refer to the previous article: Common functions/methods of random modules in Python (1)-random.seed() )

#生成一个3位小数的随机列表
print()
print("生成一个3位小数的随机列表:",[round(random.random(),3) for i in range(10)])

Insert picture description here

2. random.randint(): Generate a random integer in the specified range

Syntax: random.randint(a, b)
Parameters: a is the lower limit, b is the upper limit, the generated random number n: a <= n <= b

#生成一个1~9的随机整数
print("生成一个1~9的随机整数(1):",random.randint(1, 9))
print("生成一个1~9的随机整数(2):",random.randint(1, 9))

#生成一个10~90的随机整数
print("生成一个10~90的随机整数(1):",random.randint(10, 90))
print("生成一个10~90的随机整数(2):",random.randint(10, 90))

Insert picture description here

3. random.uniform(): Generate a random floating point number within a specified range

Syntax: random.uniform(x, y)
Note: The a and b parameters of uniform(a,b) do not need to follow the rule of a<=b, that is, a small and large b can also be used. At this time, the range of [b,a] is generated Random floating point number within.

#生成一个1~2内的随机浮点数
print("生成一个1~2内的随机浮点数(1):",random.uniform(1, 2))
print("生成一个1~2内的随机浮点数(2):",random.uniform(2, 1))

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_45154565/article/details/115342426