随机生成六位验证码函数版(python)

import random
def code(n=6,alpha=True):
    s = '' # 创建字符串变量,存储生成的验证码
    for i in range(n):  # 通过for循环控制验证码位数
        num = random.randint(0,9)  # 生成随机数字0-9
        if alpha: # 需要字母验证码,不用传参,如果不需要字母的,关键字alpha=False
            upper_alpha = chr(random.randint(65,90))
            lower_alpha = chr(random.randint(97,122))
            num = random.choice([num,upper_alpha,lower_alpha])
        s = s + str(num)
    return s
print(code(6,False))  # 打印6位数字验证码
print(code(6,True))   # 打印6位数字字母混合验证码
print(code(4,False))  # 打印4位数字验证码
print(code(4,True))   # 打印4位数字字母混合验证码

以上代码仅供参考,有问题可以留言,相互交流!

原文地址:https://www.cnblogs.com/apollo1616/p/9509407.html