random模块

发布时间 2023-12-16 13:38:36作者: ssrheart

random模块

【一】导入模块

import random

【二】随机小数

(1)默认区间的小数(random)

import random

# 默认是 大于0且小于1之间的小数
num =random.random()
print(num) # 0.50082157211298

(2)指定区间的小数(uniform)

import random

#指定为 0 到 5 之间的随机小数
res = random.uniform(1,5)
print(res) # 3.777124501595624

【三】随机整数

(1)随机区间整数(randint)

import random

# 大于等于1且小于等于5之间的整数
res = random.randint(1,5)
print(res)

(2)随机区间奇偶数(randrange)

import random

# 随机区间奇数 (开始,结束,步长)
res=random.randrange(1,10,2)
print(res)

# 随机区间偶数 (开始,结束,步长)
res=random.randrange(2,10,2)
print(res)

【四】随机选择返回

(1)随机返回一个(choice)

  • 随机选择一个返回
import random

a = [1,2,3,4]
res = random.choice(a)
print(res)

(2)随机指定个数(sample)

  • 指定待选择项和返回的个数
import random

a=[1,2,3,4]
res = random.sample(a,3)
print(res) # [1, 4, 3]

【五】打乱列表顺序(shuffle)

item = [1, 3, 5, 7, 9]
random.shuffle(item)
print(item)  # [7, 1, 5, 3, 9]

random.shuffle(item)
print(item)  # [9, 1, 5, 3, 7]

【六】练习:生成随机验证码

  • chr:用于将一个整数转换为对应的 Unicode 字符。它接受一个表示 Unicode 码点的整数作为参数,并返回对应的字符。
def codecode(x):
    code = ''
    for i in range(x):
        num = random.randint(0, 9)
        xx = chr(random.randint(97, 122))
        dx = chr(random.randint(65, 90))
        add = random.choice([num, xx,dx])
        code = "".join([code, str(add)])
    return code
print(codecode()) # CZ28

【七】生成四位验证码+登录验证

def codecode(x):
    code = ''
    # 要几位数的验证码 就循环几次
    for i in range(x):
        num = random.randint(0, 9) #随机整数
        xx = chr(random.randint(97, 122))# 随机小写ASCII码对应的英文字母
        dx = chr(random.randint(65, 90)) # 随机大写ASCII码对应的英文字母
        add = random.choice([num, xx,dx]) #随机返回一个
        code += str(add) # 拼接起来
    return code
def login():
    username=input('请输入用户名:>>>').strip()
    password=input('请输入密码:>>>').strip()
    random_code =codecode(x=4)
    print(f'当前的验证码为:>>>{random_code}')
    code = input(f'请输入验证码:>>>').strip()
    if code !=random_code:
        print('验证码错误!')
    else:
        if username =='heart' and password=='123':
            print('登陆成功')
login()