您的位置:首页 > 编程语言 > Python开发

Python3.5内置模块之random模块用法实例分析

2019-04-26 18:02 876 查看

本文实例讲述了Python3.5内置模块之random模块用法。分享给大家供大家参考,具体如下:

1、random模块基础的方法

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:ZhengzhengLiu
import random
print(random.random())     #随机产生[0,1)之间的浮点值
print(random.randint(1,6))   #随机生成指定范围[a,b]的整数
print(random.randrange(1,3))  #随机生成指定范围[a,b)的整数
print(random.randrange(0,101,2)) ##随机生成指定范围[a,b)的指定步长的数(2--偶数)
print(random.choice("hello")) #随机生成指定字符串中的元素
print(random.choice([1,2,3,4])) #随机生成指定列表中的元素
print(random.choice(("abc","123","liu"))) #随机生成指定元组中的元素
print(random.sample("hello",3))  #随机生成指定序列中的指定个数的元素
print(random.uniform(1,10))   #随机生成指定区间的浮点数
#洗牌
items = [1,2,3,4,5,6,7,8,9,0]
print("洗牌前:",items)
random.shuffle(items)
print("洗牌后:",items)

运行结果:

0.1894544287915626
2
1
74
l
2
liu
['l', 'h', 'o']
1.2919229440123967
洗牌前: [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
洗牌后: [6, 9, 2, 7, 1, 3, 8, 5, 4, 0]

2、random模块中方法的实际应用――生成随机验证码

(1)随机生成4位纯数字验证码

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:ZhengzhengLiu
import random
check_code = ''  #最终生成的验证码
for i in range(4):    #4位长的纯数字验证码
cur = random.randint(0,9)
check_code += str(cur)
print(check_code)

运行结果:

0671

(2)随机生成4位字符串验证码(数字与字符都有)

import random
check_code = ''
for i in range(4):
cur = random.randrange(0,4)  #随机猜的范围,与循环次数相等
#字母
if cur == i:
tmp = chr(random.randint(65,90))  #随机取一个字母
#数字
else:
tmp = random.randint(0,9)
check_code += str(tmp)
print(check_code)

运行结果:

39HN

PS:这里再提供几款相关工具供大家参考使用:

在线随机数生成工具:
http://tools.jb51.net/aideddesign/rnd_num

在线随机生成个人信息数据工具:
http://tools.jb51.net/aideddesign/rnd_userinfo

在线随机字符/随机密码生成工具:
http://tools.jb51.net/aideddesign/rnd_password

在线随机数字/字符串生成工具:
http://tools.jb51.net/aideddesign/suijishu

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python数学运算技巧总结》、《Python字符串操作技巧汇总》、《Python编码操作技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

希望本文所述对大家Python程序设计有所帮助。

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: