random模块
random 模块
随机:在某个范恩内取到每一个值的概率是相同的
用于:抽奖,彩票,随机红包,验证码,洗牌
随机小数
import random #随机小数 ret = random.random() # [0,1)之内的随机小数 ret = random.uniform(1,5) # [1,5)之间的随机小数
随机整数
#随机整数 ret = random.randint(1,2) # [1,2] 范围内的随机整数 ret = random.randrange(1,2) # [1,2) 范围内的随机整数 ret = random.randrange(1,10,2) #[1,10) 内的随机奇数
随机抽取一个值或多个值
##随机抽取一个值 lst = [1,2,3,'a',('b','c')] ret = random.choice(lst)
##随机抽取多个值 两个值或多个值不重复 ret = random.sample(lst,2) #第二个参数是抽取值的个数
打乱顺序:在原列表的基础上打乱,改变原列表
#打乱顺序-在原列表的基础上做乱序 lst2 = [1,2,3,'a',('b','c')] random.shuffle(lst2)
生成四位随机验证码0-9
##基础版本 code = '' for i in range(4): #code+=(str(random.randint(0,9))) num = random.randint(0,9) code += str(num) print(code)
##函数版本 def rand_code(n=4): code = '' for i in range(n): code += str(random.randint(0,9)) return code print(rand_code()) print(rand_code(6))
随机生成6位 数字+字母 验证码
##基础版 code = '' for i in range(6): rand_num = str(random.randint(0,9)) rand_alph = chr(random.randint(97,122)) rand_alph_upper = chr(random.randint(65,90)) atom_code = random.choice([rand_num,rand_alph,rand_alph_upper]) code += atom_code print(code)
##函数版本 def rand_code2(n=6): code = '' for i in range(n): rand_num = str(random.randint(0,9)) rand_alph = chr(random.randint(97,122)) rand_alph_upper = chr(random.randint(65,90)) atom_code = random.choice([rand_num,rand_alph,rand_alph_upper]) code += atom_code return code print(rand_code2()) print(rand_code2(8))
数字 或 数字+字母 验证码
def rand_code3(n=6,alph_flag=True): code = '' for i in range(n): rand_num = str(random.randrange(0,9)) if alph_flag: rand_alph = chr(random.randint(97,122)) rand_alph_upper = chr(random.randint(65,90)) rand_num = random.choice([rand_num,rand_alph,rand_alph_upper]) code += rand_num return code print(rand_code3(5))