random模块

1.基本用法

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 # Author:James Tao
 4 import random
 5 
 6 print(random.random())#生成0-1之间的随机浮点数
 7 
 8 print(random.uniform(1,3))#生成1-3之间的随机浮点数
 9 
10 print(random.randint(1,3))#生成1-3之间的整数,前后都能取到
11 
12 print(random.randrange(1,3))#生成1-3之间的整数,包含1不包含3
13 
14 print(random.choice('asdas'))#a、元组、列表、字符串,产生随机值
15 
16 print(random.sample('hello',2))#从字符串中随机取两位返回
17 
18 L=[1,2,3,4,5]
19 random.shuffle(L)#洗牌,打乱顺序
20 print(L)

运行结果:

2.运用random模块编写验证码生成模块

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 # Author:James Tao
 4 
 5 #使用random模块生成验证码
 6 
 7 import random
 8 
 9 checkcode=''
10 
11 code_length=6#长度固定为6
12 
13 for i in range(code_length):
14 
15     currentcode=random.randrange(0,code_length)
16 
17     if i==currentcode:
18         tempcode=chr(random.randint(65,90))#获取ASCII表中65到90之间对应字母
19     else:
20         tempcode=str(random.randint(0,9))#转换成字符串
21 
22     checkcode+=tempcode#字符串拼接
23 
24 print(checkcode)
原文地址:https://www.cnblogs.com/BIT-taozhen/p/9864801.html