random模块
import random
# 浮点数
random.randon() # 0< 随机浮点数 < 1
random.uniform(1,3) # 1< 随机浮点数 < 3
# 整数
random.randint(1,10) # 1<= 随机整数 <=10
random.radrange(1,10) # 1<= 随机整数 < 10
# 可迭代对象
random.choice( 可迭代对象 )
random.choice( [1,'aaa',[44,55]] ) # 随机取一个,取出来什么类型就是什么类型
# >>> 1 / aaa / [44, 55]
# 抽奖活动
import random
random.choices( 可迭代对象,weights=设置每一个权重,k=取出几个数 )
print(random.choices([1, 2, 3, 4, 5, 6], weights=[98, 98, 98, 98, 98, 10], k=1))
# 6 概率为 10/500 0.02
random.sample( 可迭代对象, 选取个数 )
random.sample( [1,'aaa',333,444,555], 2 ) # 随机取两个,放入列表中
# >>> [1, 'aaa']
# 打乱顺序--'洗牌'
item = [1, 3, 4, 5, 6, 7, 8, 9]
random.shuffle(item)
print(item)
# >>> [6, 9, 7, 5, 8, 1, 4, 3]
案例:随机验证码
ASCII码
chr(65) --->'A'
ord('A') ---> 65
import random
res= ''
for i in range(6):
26大写字母随机取一个 = chr( random.randint(65,90) )
10个数字随机取一个 = str( random.randint(0,9) )
随机字符 = random.choice([26大写字母随机取一个,10个数字随机取一个])
res += 随机字符
print(res)
# >>> W583Q7