Random模块

random模块用来生成随机的数字或字母

#-*- coding:utf-8 -*-
__author__ = "MuT6 Sch01aR"

import random

print random.random()  #随机0-1之间的数
print random.uniform(1,10)  #随机1-10之间的数

print random.randint(1,10)  #随机1-10之间的整数
print random.randrange(1,10) #随机1-9之间的整数

print random.choice('hello') #从字符串或列表中随机取
print random.sample('fuck you',2) #随机取两个字母

#随机列表
a = [1,2,3,4,5,6]
random.shuffle(a)
print a

用random写个小程序,生成随机验证码

#-*- coding:utf-8 -*-
__author__ = "MuT6 Sch01aR"

import random

checkcode = ''

for i in range(5):
    current = random.randint(0,5)
    if current == i:
        tmp = chr(random.randint(65,90))
    else:
        tmp = random.randint(0,9)
    checkcode += str(tmp)

print (checkcode)

小程序的执行效果

原文地址:https://www.cnblogs.com/sch01ar/p/7570132.html