zoukankan      html  css  js  c++  java
  • Python基础-----random随机模块(验证码)

    random随机模块的用法及功能

    import random
    
    print(random.random())#(0,1)----获取0-1中的一个float
     
    print(random.randint(1,3))  #[1,3]取范围内的一个整数
     
    print(random.randrange(1,3)) #[1,3)取范围内的一个整数
     
    print(random.choice([1,'23',[4,5]]))#23 随机获取可迭代对象中的一个元素
     
    print(random.sample([1,'23',[4,5]],2))#[[4, 5], '23'] 两个参数,参数1为可迭代对象,参数2为随机选取可迭代对象元素的个数
     
    print(random.uniform(1,3))#1.927109612082716   获取指定范围中的一个float
     
     
    item=[1,3,5,7,9]
    random.shuffle(item)   #随机打乱顺序
    print(item)

    例子:利用random模块随机生成四位大小写字母和数字组合的验证码,用户输入不分大小写进行验证

      如果用户输入错误3次,则无法继续。

    def check_code():
        import random
        out_code = ""
    
        for i in range(4):
            capital_letter = chr(random.randint(65,90))
            lowercase_letter = chr(random.randint(97,122))
            int_num = random.randint(0,9)
            ccode = [capital_letter,lowercase_letter,int_num]
            out_code += str(random.choice(ccode))
        return out_code
    
    if __name__ == '__main__':
        tag = True  #标识状态,输入错误三次则无法继续
        i = 1        #计数
        while tag:
            if i > 3:
                print('已失败3次,请稍后再试!')
                tag = False
                break
            else:
                code = check_code()
                print('本次的验证码是:%s'%code)
                inp = input('请输入验证码:')
                if inp.upper() == code.upper():
                    print("输入正确~!")
                    break
                else:
                    i += 1
                    print("输入错误,请重试!")
  • 相关阅读:
    MPF源码分析之资源文件加载
    oracle存储过程代码日志记录
    fix8源码分析之日志模块
    oracle日期转整数
    记录OCI操作一个诡异的问题
    记录一个虚拟机重启网络启动失败问题
    buff占用内存高
    MFC程序编译链接问题汇总一
    回调函数模型设计
    利用call与apply向函数传递参数
  • 原文地址:https://www.cnblogs.com/Meanwey/p/9741310.html
Copyright © 2011-2022 走看看