python-标准库random模块的使用

python-标准库random模块

1. python-标准库random模块

  • random库用于生成随机数。

    方法 描述
    random.randint(a,b) 随机返回整数a和b范围内数字
    random.random() 生成随机数,它在0和1范围内
    random.randrange(start, stop[, step]) 返回整数范围的随机数,并可以设置只返回跳数
    random.sample(array, x) 从数组中返回随机x个元素
    choice(seq) 从序列中返回一个元素

2. 案例

  • 案例1、random-基础使用

    #!/usr/bin/env python3
    # _*_ coding: utf-8 _*_
    # Author:shichao
    # File: .py
    
    import random
    
    # 随机返回整数a 和 b范围内数字
    print(random.randint(1,10))
    
    # 生成随机数,它在0和1范围内
    print(random.random())
    
    
    # 随机返回整数
    print(str(random.randint(0,9)))
    
    # 随机返回大写字母
    print(chr(random.randint(65,90)))          # 输出大写字母,是从65-90
    
    # 随机返回小写字母
    
    print(chr(random.randint(97,122)))        # 输出小写字母,是从97-122
    
    
  • 案例2、random-生成验证码

    #!/usr/bin/env python3
    # _*_ coding: utf-8 _*_
    # Author:shichao
    # File: .py
    
    import random
    
    # 练习题: 随机生成四为验证码
    '''
    四位验证码: 一个一个的生成
    可能会有数字,可能会有大写字母,可能会有小写字母
    '''
    def rand_num():
        return str(random.randint(0,9))
    
    def rand_upper():
        return chr(random.randint(65,90))           # 输出大写字母,是从65-90
    
    def rand_lower():
        return chr(random.randint(97,122))          # 输出小写字母,是从97-122
    
    
    def rand_verify_code(n=4):
        lst = []    # 添加存储的列表
        for i in range(n):
            which = random.randint(1,3)
            if which == 1:
                s = rand_num()       # 随机数字
            elif which == 2:
                s = rand_upper()      #  随机大写字母
            elif which == 3:
                s = rand_lower()      # 随机小写字母
            lst.append(s)
        return "".join(lst)
    
    a = rand_verify_code()
    print(a)
    
    z = input("请你输入验证码:")
    
    if  a == z :
        print("你输入正确")
    else:
        print("验证码输入错误,请重试")
    
    
posted @ 2023-01-13 10:06  七月流星雨  阅读(72)  评论(0编辑  收藏  举报