import random
random.random() 产生0-1间的随机小数
>>> res = random.random()
>>> print(res)
0.027542593093386247
>>> res = random.random()
>>> print(res)
0.7959514300797362
random.randint(start_num,end_num) 产生指定起终止值中的随机整数,闭合区间 [start_num,end_num],可取到起终止值
>>> res = random.randint(1,11)
>>> print(res)
9
>>> res = random.randint(1,11)
>>> print(res)
3
random.randrange(start_num,end_num) 产生指定起终止值中的随机整数,半开区间[start_num,end_num)
>>> res = random.randrange(1,10)
>>> print(res)
5
random.uniform(start_num,end_num) 产生指定起终止值中的随机小数,全开区间(start_num,end_num)
>>> res = random.uniform(1,10)
>>> print(res)
9.22286461152352
>>> res = random.uniform(1,10)
>>> print(res)
2.7524663134138456
>>> res = random.uniform(1,10)
>>> print(res)
4.339277966397103
randon.choice(iter) 在单列集合iter中随机选出一个元素
>>> k = [1,2,"","name",12]
>>> res = random.choice(k)
>>> print(res)
2
>>> res = random.choice(k)
>>> print(res)
12
random.sample(iter,n) 在单列集合中随机取出n个元素组成列表返回
>>> k = [1,2,"","name",12]
>>> res = random.sample(k,3)
>>> print(res)
[1, '', 'name']
>>> res = random.sample(k,3)
>>> print(res)
['', 12, 'name']
random.shuffle(iter) 将列表元素顺序打散,不产生新的列表
>>> print(k)
[12, 'name', '', 1, 2]
>>> res = random.shuffle(k)
>>> print(k)
['', 'name', 2, 12, 1]
>>> res = random.shuffle(k)
>>> print(k)
[12, 'name', 1, 2, '']
>>>
实例:
# 产生指定位数的验证码
import random
def random_code(count):
code = ''
for i in range(count):
num = random.randint(1, 3)
if num == 1:
tag = str(random.randint(0, 9))
elif num == 2:
tag = chr(random.randint(65, 90))
else:
tag = chr(random.randint(97, 122))
code += tag
return code
print(random_code(6))