random模块
import random print(random.random()) # 大于0且小于1之间的小数 print(random.randint(1, 6)) # 大于等于1且小于等于6之间的整数 print(random.randrange(1, 6)) # 大于等于1且小于6之间的整数 print(random.choice([1, 2, 3, [4, 5, 6]])) # 1,2,3或[4,5,6] print(random.sample([1, 'a', [4, 5, 6]], 2)) # 列表元素任意2个组合 print(random.uniform(1, 3)) # 大于1小于3的小数,如2.5186390629964013 item = [1, 2, 3, 4, 5, 6] random.shuffle(item) # 打乱item的顺序,相当于"洗牌" print(item)
生成随机验证码
import random def make_code(n=5): res = '' for i in range(n): s1 = chr(random.randint(65, 90)) s2 = str(random.randint(0, 9)) res += random.choice([s1, s2]) return res print(make_code(6))