random模块

时间:2019-11-16
本文章向大家介绍random模块,主要包括random模块使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

一、random模块

一、random模块
import random
# 大于0且小于1之间的小数
print(random.random())
0.42866657593385415
# 大于等于1且小于等于3之间的整数
print(random.randint(1, 3))
3
# 大于等于1且小于3之间的整数
print(random.randrange(1, 3))
2
# 大于1小于3的小数,如1.927109612082716
print(random.uniform(1, 3))
2.1789596280319605
# 列表内的任意一个元素,即1或者‘23’或者[4,5]
print(random.choice([1, '23', [4, 5]]))
[4, 5]
# random.sample([], n),列表元素任意n个元素的组合,示例n=2
print(random.sample([1, '23', [4, 5]], 2))
['23', 1]
lis = [1, 3, 5, 7, 9]
# 打乱l的顺序,相当于"洗牌"
list1 = ['红桃A', '梅花A', '红桃Q', '方块K']
random.shuffle(list1)
print(list1)
# 默认获取0——1之间任意小数
res2 = random.random()
print(res2)
# 需求: 随机验证码
'''
需求: 
    大小写字母、数字组合而成
    组合5位数的随机验证码
    
前置技术:
    - chr(97)  # 可以将ASCII表中值转换成对应的字符
    # print(chr(101))
    - random.choice
'''


# 获取任意长度的随机验证码
def get_code(n):
    code = ''
    # 每次循环只从大小写字母、数字中取出一个字符
    # for line in range(5):
    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(100)
print(code)
print(len(code))

原文地址:https://www.cnblogs.com/lvguchujiu/p/11873885.html