random模块

random 模块

import random
# 随机小数
print(random.random()) # 0.9034034434451242 大于零小于一的小数
print(random.uniform(1, 3))# 大于1小于3的随机小数
# 随机整数
print(random.randint(1, 2)) # 1or 2  大于等于一小于等于二的随机整数
print(random.randrange(1, 17, 2)) # 大于等于1且小于17的随机奇数
# 随机返回
print(random.choice([1, "a", 12, (2, 3)])) # 随机选择列表的一个元素返回
# 随机选择多个返回,返回的个数为函数的第二个参数
print(random.sample([1, "a", 12, (2, 3)], 2)) # 随机选择列表的俩个元素返回
# 打乱列表顺序
l = [1,3,5,8,9]
random.shuffle(l)
print(l) # [1, 8, 5, 9, 3]
s = ''
for i in range(4):
    ret = random.randint(1, 9)
    s += str(ret)
print(s) # 随机四位数字验证码
# 六位数字+字母的随机验证码
s = ""
for i in range(6):
    nub = random.randint(0, 9)
    upper_al = chr(random.randint(65, 90)) # 用内置函数chr()来获取大写字母
    lower_al = chr(random.randint(95, 122)) # 获取小写字母
    ret1 = random.choice([str(nub), upper_al, lower_al])
    s += ret1
print(s)
>>>>>>>>>>>>>>>
e4pZK6
验证码小程序
# 验证码进阶
# 4位数字验证码
# 6位数字验证码
# 6位数字+字母验证码
def func(n=6,alph=True):
    s = ''
    for i in range(n):
        if alph:
            nub = str(random.randint(0, 9))
            alpha_upper = chr(random.randint(65, 90))
            alpha_lower = chr(random.randint(97, 122))
            ret = random.choice([nub, alpha_lower, alpha_upper])
            s = s + ret
        else:
            nub = random.randint(0, 9)
            s += str(nub)
    return s
print(func()) 
print(func(4))
print(func(4, False))
print(func(6, False))
>>>>>>>>>>>>>>>>>>>>
pEncjo
335B
7469
767696

 

posted on 2018-08-20 16:17  yw1229  阅读(124)  评论(0编辑  收藏  举报

导航