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("输入错误,请重试!")

 

posted @ 2018-10-03 23:38  Meanwey  阅读(552)  评论(0编辑  收藏  举报