ramdom 随机数模块

random随机数模块

import random
print(random.random()) # 随机产生0-1之间的小树 0.2607238052420794
print(random.randint(1, 9)) # 随机产生指定范围的整数 8
print(random.uniform(1, 2)) # 随机产生指定范围的小数 1.957561091011393
print(random.choice(['特等奖', '一等奖', '二等奖', '谢谢惠顾']))
# 从指定列表中随机抽取
print(random.sample(['浙江省', '宁波市', '杭州市', '上海市'],2))
# ['宁波市', '杭州市']  随机抽取指定样本量

import random

l = [1,2,3,4,5,6,7,8,9,0]
random.shuffle(l)
print(l)
# [9, 2, 3, 6, 1, 5, 8, 0, 4, 7] 将列表中的数据打乱重新排序

搜狗公司的笔试题

# 随机验证码可以是由 数字 小写字母 大小写字母 任意组合,编写能够产生五位数的随机验证码
# 普通版
e = ''
for i in range(5):
    # 先定义数字 0 - 9
    # 讲类型转换为字符串
    a = str(random.randint(0, 9))
    # 定义大写字母
    b = chr(random.randint(65, 90))
    # 定义小写字母
    c = chr(random.randint(97, 122))
    d = random.choice([a, b, c])
    e += d

print(e)
  • 搜狗公司笔试题函数封装版本
def get_code(n):
    # 提前定义一个存储验证码的变量
    e = ''
    for i in range(n):
        # 先定义数字 0 - 9
        # 讲类型转换为字符串
        a = str(random.randint(0, 9))
        # 定义大写字母
        b = chr(random.randint(65, 90))
        # 定义小写字母
        c = chr(random.randint(97, 122))
        d = random.choice([a, b, c])
        e += d
    return e
e1 = get_code(4)
e2 = get_code(5)
print(e1)
print(e2)

溜了溜了

posted @ 2021-11-26 20:45  谢俊杰  阅读(235)  评论(0编辑  收藏  举报