python生成随机验证码

一、生成随机验证码(纯数字及字母加数字):

import random
import string

checkcod=''
for i in range(5):  #5位验证码
    '''
    #纯数字验证码
    #随机值1-9取可以保证5位,如果是1-12就会出现5位以上验证码
    current=random.randint(1,9)
    #i数据类型转换成字符串类型
    #checkcod+=str(i)
    checkcod+=str(current)
    '''

    #数字加字母验证码   循环5次:猜的值和当前循环i值是否相等
    current=random.randrange(0,5)
    if current == i:                
        #猜的值与当前i循环值相等就会执行下面tmp值为字母
        tmp=chr(random.randint(65,90))
                #把十进制数字转换成字母用chr(65到90是获取大写字母
        #chr(65)是大A chr(90)是大写
        #获取65到90用random.randint()       
    else:
        # 否则就是猜的值与当前i值不相等,就会是纯数字
        tmp=random.randint(0,9)
    checkcod+=str(tmp)
print(checkcod)

二、生成随机验证码(字母加数字):

import random
checkcode = ''
for i in range(4):
    current = random.randrange(0,4)
    if current != i:     #!=  不等于 - 比较两个对象是否不相等
        temp = chr(random.randint(65,90))
    else:
        temp = random.randint(0,9)
    checkcode += str(temp)
print (checkcode)

用!=这个方法获取的值是字母+数字,而==这个方法是有时循环为数字+字母、有时循环为纯数字的。

猜你喜欢

转载自blog.51cto.com/meiling/2116184