python-----内置模块之random模块
random.random()---随机[0,1)的浮点数
random.randint(1,3)---随机1到3的整数[1,3]
random.randrange(1,3)----1,2
random.choice('hello') random.choice([1,2,3])----序列中随机取
random.sample('hello',2)-------序列中随机取两个
random.uniform(1,3)-----取浮点数
a=[1,2,3,4,5,6]
random.shuffle(a)-----洗牌功能
验证码的应用
这是数字的验证码的应用:
import random checkcode='' for i in range(4): current=random.randint(1,9) checkcode+=str(current) print(checkcode)
这是数字加字母的验证码的应用:
1 import random 2 checkcode='' 3 for i in range(4): 4 current=random.randrange(0,4) 5 #随机字母 6 if current==i: 7 tmp=chr(random.randint(65,90)) 8 #随机数字 9 else: 10 tmp=random.randint(0,9) 11 12 checkcode+=str(tmp) 13 print(checkcode)
需要5位时只需要改动4这个值
for i in range(4)
current=random.randrange(0,4)