random模块
# 随机 : 在某个范围内取到每一个值的概率是相同的
1、随机小数
import random
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、随机抽取
# 随机抽取一个值
lst = [1,2,3,'aaa',('wahaha','qqxing')]
ret = random.choice(lst)
print(ret)
# 随机抽取多个值
ret = random.sample(lst,2)
print(ret)
4、随机打乱排序
在原列表的基础上做乱序,针对的是列表,返回值是None
lst = [1,2,3,'aaa',('wahaha','qqxing')]
random.shuffle(lst)
print(lst)
作业:
1:随机生成4位数字验证码
import random
# ret = random.randint(0000,9999)
# print(ret)
def rand_code(n=4):
code = ''
for i in range(n):
num = random.randint(0,9)
code = code + str(num)
return code
print(rand_code())
print(rand_code(6))
2:随机生成6位数字加字母的验证码:
#97-122 :a-z 65-90:A-Z
import random
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 = str(chr(random.randint(97,122)))
rand_alph_upper = str(chr(random.randint(65,90)))
rand_num = random.choice([rand_num,rand_alph,rand_alph_upper]) #重要
code = code + rand_num
return code
print(rand_code())