random 模块

一、随机模块

二、随机小数

  0-1之内的随机小数

  random.random()

  任何范围内的随机小数

  random。uniform(1,5)

三、随机整数

  random.randint(1,2)  随机整数,顾头顾尾

  random.randrange(1,2) 随机整数,顾头不顾尾

  random.randrange(1, 10, 2) 随机整数, 抽取1-10内的奇数

四、随机抽取

  random.choice(***)   随机抽取一个数

  random.samplie(***,***)    随机抽取多个数(可以控制抽取的数量)

五、打乱顺序

  random.shuffle()                                                                                                                                                                                                                                                                                                                                                          

六、写一个随机验证码,长度默认为六位数,有数字有字母。

  

import random
code = ''
    def fn(n = 6, aa = True)
        for i in range(n):
            a = random.randint(0,9)
            if aa :
                b = chr(random.randint(65,90))
                c = chr(random.randint(97,122))
                a = random.choice([a,b,c])
            code += str(a)
        return code
print(fn())             #默认生成随机刘伟验证码

print(fn(n=4 , aa = False))      #随机生成四位
随机生成验证码

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          

原文地址:https://www.cnblogs.com/wf123/p/9443113.html