码迷,mamicode.com
首页 > 编程语言 > 详细

python之-- random模块

时间:2017-05-09 22:25:42      阅读:205      评论:0      收藏:0      [点我收藏+]

标签:分享   提取   ide   int   大写   img   logs   sam   imp   

random模块
random.random():随机打印一个小数
random.randint(1,10):随机打印1-10之间的任意数字(包括1和10)
random.randrange(1,10):随机打印1-10之间的任意数字(不包括10)
random.sample(range(100),5):从100个数字中随机抽取5个数字以列表形式打印。可以用作随机验证码或密码使用
如:random.sample(‘abcde‘,3) 随机生成3个字符。
举例:生成随机验证码
第一种写法
技术分享
1 import string,random
2 #通过string模块生成大小写字母和0-9数字
3 s = string.ascii_letters+string.digits
4 #从所有字母和数字中随机提取6个数字
5 print(‘‘.join(random.sample(s,6)))  #验证码
View Code

第二种写法:
技术分享
 1 import random
 2 info = ‘‘
 3 #循环6次表示验证码为6位
 4 for i in range(6):
 5     #随机生成0-6之间的数字,不包括6,和上面的循环对应
 6     curr = random.randrange(0,6)
 7     # 如果循环中出现的数字正好和这里随机生成的数字对应上,则生成数字
 8     if curr == i:
 9         temp = random.randint(0,9)
10     else:
11     # 否则生成大写字符
12         temp = chr(random.randint(65,90))
13      #拼出6为字符为验证码
14     info += str(temp)
15 print(info)
View Code

python之-- random模块

标签:分享   提取   ide   int   大写   img   logs   sam   imp   

原文地址:http://www.cnblogs.com/zy6103/p/6832946.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!