首页 > 其他 > 详细

random模块

时间:2019-11-19 21:00:34      阅读:92      评论:0      收藏:0      [点我收藏+]

random模块

import random
#随机获取1-9中任意真整数
res = random.randint(1,9)
print(res)

#默认获取0-1之间任意小数
res2 = random.random()
print(res2)

#洗牌,将可迭代对象中的值进行乱序
list1 = ['A','B','C','D']
random.shuffle(list1) #无返回值
print(list1)
>>>['D', 'C', 'A', 'B']

#随机获取可迭代对象中的某一个值
['D', 'C', 'A', 'B']
res3 = random.choice(list1) # 无返回值
print(res3)
>>>'D'

需求: 随机验证码

'''
需求:
    大小写字母、数字组合而成
    组合任意长度的随机验证码
前置技术:
    -chr() #转化为ASCII中对应的字符
    -random.choice
'''
import random


def get_code(n):
    code = ''
    #每次循环只从大小写字母、数字中取出一个字符
    for line in range(n):
        #随机获取一个小写字母
        res1 = random.randint(97,122)
        lower_str = chr(res1)
        
        #随机获取一个大写字母
        res2 = random.randint(65,90)
        upper_str = chr(res2)
        
        #随机获取一个数字
        number = str(random.randint(0,9))
        
        #随机从获取的大小写字母、数字中获取一个元素
        code_list = [lower_str, upper_str, number]
        random_code = random.choice(code_list)
        code += random_code
        
    return code
        
code = get_code(5)
print(code)
print(len(code))
>>>
    5v0lX
    5
    
    

random模块

原文:https://www.cnblogs.com/littleb/p/11892258.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!