random模块

时间:2022-06-09
本文章向大家介绍random模块,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
>>> import random
>>> random.random()      # 大于0且小于1之间的小数
0.7664338663654585

>>> random.randint(1,5)  # 大于等于1且小于等于5之间的整数
2

>>> random.randrange(1,3) # 大于等于1且小于3之间的整数
1

>>> random.choice([1,'23',[4,5]])  # #1或者23或者[4,5]
1

>>> random.sample([1,'23',[4,5]],2) # #列表元素任意2个组合
[[4, 5], '23']

>>> random.uniform(1,3) #大于1小于3的小数
1.6270147180533838

>>> item=[1,3,5,7,9]
>>> random.shuffle(item) # 打乱次序
>>> item
[5, 1, 3, 7, 9]
>>> random.shuffle(item)
>>> item
[5, 9, 7, 1, 3]

生成验证码

复制代码
import random

def v_code():

    code = ''
    for i in range(5):

        num=random.randint(0,9)
        alf=chr(random.randint(65,90))
        add=random.choice([num,alf])
        code="".join([code,str(add)])

    return code

print(v_code())
复制代码