random模块

random模块

  • 定义:随机生成整数 / 小数 / 指定列表值某个元素

【一】随机生成小数

【1】默认区间的小数 区间0-1之间的小数

复制代码
import random
print(random.random())      # 0.5858839340258046

【2】指定区间 给定区间内的小数

复制代码
import random
print(random.uniform(4,8 ))     # 7.467665328012298

【二】随机生成整数

【1】指定区间的整数 给定区间内的整数

复制代码
import random
print(random.randint(1,10))     # 8

【2】随机区间内的奇偶数

复制代码
import random
print(random.randrange(1,20,2))     # 1,3,5
print(random.randrange(1,20,3))     # 2,4,6

【三】随机返回值

【1】返回一个元素

先创建一个可迭代类型

复制代码
num_list = [i for i in range(1, 10)]
num_list += ['a', 'b', 'c']
print(random.choice(num_list))      # 输出abc 或者数字

【2】一次性返回多个元素

(1)以列表的形式返回结果
复制代码
num_list = [i for i in range(1, 10)]
num_list += ['a', 'b', 'c']
print(random.choices(num_list))     # [4]
(2)以指定关键字 k 指定返回列表中的元素个数
复制代码
num_list = [i for i in range(1, 10)]
num_list += ['a', 'b', 'c']
print(random.choices(num_list, k=3))    # ['c', 4, 1]
print(random.choices(num_list, 3))      # 与上面一条命令结果一样,默认值就是k

【四】打乱顺序

random.shuffle()

复制代码
num_list = [i for i in range(1,10)]
print(num_list)             # [1, 2, 3, 4, 5, 6, 7, 8, 9]
random.shuffle(num_list)    # 打乱顺序
print(num_list)         # [2, 3, 1, 8, 6, 5, 4, 7, 9]
​

【五】随机生成验证码

  • 随机大小写字母 + 随机数字

  • chr(数字) ---> 返回指定ASCII码对应的字符

  • 做一个能生成6位的验证码

复制代码
import random

def v_code(n):
    code=''
    for i in range(n):
        random_int = str(random.randint(0, 9))      # 0~9之间的整数
        random_upper = chr(random.randint(65,90))   # A~Z的大写字母
        random_lower = chr(random.randint(97,122))  # a~z的小写字母
        temp = random.choice([random_int, random_upper, random_lower])
        code += temp
    return code

result = v_code(6)
print(result)
相关推荐
小白勇闯网安圈9 小时前
day_2
python
山楂树の9 小时前
Java 泛型:泛型类、泛型方法、泛型接口与通配符
java·开发语言·笔记
叮当小飞鱼9 小时前
RAG幻觉
python
利威尔xu9 小时前
2026-11-18-Go接口幂等设计实战
开发语言·后端·golang
赵大仁9 小时前
Agent 工具调用可靠性:超时、重试、幂等与人工确认怎么设计
python·agent·幂等·工具调用·人工确认
eggwyw10 小时前
linux下的C\C++多进程多线程编程实例详解
开发语言·c++
布莱克60510 小时前
Swift 枚举详解:从基础语法到关联值与模式匹配
开发语言·ios·swift·枚举
__underline__10 小时前
冷门Python知识点007篇:list[int]不是类,为什么能当基类?
后端·python
Dmz丶10 小时前
前端转 AI 100 天 Day 49:文档切分——RAG 效果的隐形开关
python
布莱克60511 小时前
Swift 闭包详解:从语法到实战的完整指南
服务器·开发语言·ios·ssh·swift·闭包