random模块
【一】导入模块
【二】随机小数
(1)默认区间的小数(random)
| import random |
| |
| |
| num =random.random() |
| print(num) |
| import random |
| |
| |
| res = random.uniform(1,5) |
| print(res) |
【三】随机整数
(1)随机区间整数(randint)
| import random |
| |
| |
| 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) |
【五】打乱列表顺序(shuffle)
| item = [1, 3, 5, 7, 9] |
| random.shuffle(item) |
| print(item) |
| |
| random.shuffle(item) |
| print(item) |
【六】练习:生成随机验证码
- 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()) |
【七】生成四位验证码+登录验证
| 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 += 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() |
本文作者:ssrheart
本文链接:https://www.cnblogs.com/ssrheart/p/17908746.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步