1 随机一个0-1之间float
>>> random.random() 0.82544262519395 >>> random.random() 0.11485429482423948 >>>
2 随机一个1-3之间的整数
>>> random.randint(1,3) 3 >>> random.randint(1,3) 1 >>> random.randint(1,3) 2 >>>
这个也是
>>> random.randrange(1,4)
3
>>> random.randrange(1,4)
1
>>> random.randrange(1,4)
3
>>>
3 其他
>>> random.choice('hello') 'o' >>> random.sample('hello',2) ['h', 'l'] >>> random.uniform(0,3) 2.306228935494692 >>> l = [1,2,3,4,5,6,7,8,9] >>> random.shuffle(l) >>> l [9, 5, 2, 8, 7, 4, 6, 3, 1] >>>
4 随机生成验证码
checkcode = '' for i in range(5): current = random.randrange(0,5) #字母 if current == i: tmp=chr(random.randint(65,90)) #数字 else: tmp=random.randint(0,9) checkcode += str(tmp) print(checkcode)