random模块
1. 基础语法
import random print(random.random()) # (0,1)--->float 大于0且小于1之间的小数 print(random.randint(1, 3)) # [1,3] 大于等于1且小于等于3之间的整数 print(random.randrange(1, 3)) # [1,3) 大于等于1且小于3之间的数 print(random.choice([111, 'aaa', [4, 5]])) # 1或者'aaa'或者[4,5] print(random.sample([111, 'aaa', 'ccc', 'ddd'], 2)) # 列表元素任意两个组合 print(random.uniform(1, 3)) # 大于1且小于3的小数 item = [1, 3, 5, 7, 9] random.shuffle(item) # 打乱item顺序,可以看作洗牌 print(item)
2. 应用
随机验证码
def random_code(): import random code = '' for i in range(6): a = str(random.randint(0, 9)) b = chr(random.randint(ord('a'), ord('z'))) c = chr(random.randint(ord('A'), ord('Z'))) res = random.choice([a,b,c]) code += res return print(code) random_code()

浙公网安备 33010602011771号