25 -3 random模块
随机的概念:
在某个范围内取到每一个值的概率是相同的
1、随机小数
print(random.random()) # 0-1之内的随机小数 print(random.uniform(1,5)) # 任意范围之内的随机小数
2、随机整数 (重要)
print(random.randint(1,2)) # [1,2] 包含2在内的范围内随机取整数 print(random.randrange(1,2)) # [1,2)不包含2在内的范围内随机取整数 print(random.randrange(1,10,2)) # [1,10)不包含10在内的范围内随机取奇数
3、随机抽取 -----choice、sample
1)随机抽取一个值 choice(列表)
lst = [1,2,3,'aaa',('zxd','cyy')] ret = random.choice(lst) print(ret) # 从列表中抽取一个值取出来
2)随机抽取多个值 sample(列表,个数)
lst = [1,2,3,'aaa',('zxd','cyy')] ret = random.sample(lst,2) print(ret) #取出两个值
4、打乱顺序 ---shuffle(列表)
对原列表操作
lst = [1,2,3,'aaa',('zxd','qqxing')] random.shuffle(lst) print(lst)
小试牛刀:
需求:生成4位数字的随机验证码
code = '' for i in range(4): num = random.randint(0,9) code += str(num) print(code)
def rand_code(n=4): code = '' for i in range(n): num = random.randint(0, 9) code += str(num) return code print(rand_code()) print(rand_code(6)) # 巧妙之处在于默认是4为验证码,也可以人为修改位数,例如上面扩充到6位
扩充知识点:
a的ascill码 为97
z 为122
print(chr(97)) #a print(chr(122)) #z
print(chr(65)) # A
print(chr(90)) # Z
需求升级:数字+字母 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)
import random def rand_code(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 ret = rand_code() print(ret)
嘿! 再次升级: 我可以设置全数字或者数字+字母形式的验证码
def rand_code(n=6, alph_flag=True): code = '' for i in range(n): rand_num = str(random.randint(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 ret = rand_code(n=4) print(ret)