python 19 random随机模块

random
首先导入模块
import random

随机小数
print(random.random())  # 大于0小于1之间的小数
print(random.uniform(1,3))  # 大于1小于3的小数

随机整数
print(random.randint(1,5))  # 大于等于1且小于等于5之间的整数
print(random.randrange(1,10,2))  # 大于等于1且小于10之间的奇数

随机选择一个返回
print(random.choice([1,'23',[4,5]])) # 1或者'23'或者[4,5]
随机选择多个返回,返回的个数为函数的第二个参数
print(random.sample([1,2,5,8],2))  # 列表元素任意2个

打乱列表顺序
item = [1,3,5,7,9]
random.shuffle(item)
print(item)
random.shuffle(item)
print(item)

生成随机验证码
import random
def v_code():
    code = ''
    for i in range(5):
        num = random.randint(0,9)
        alf = chr(random.randint(65,90))
        add = random.choice([num,alf])
        code = ''.join([code,str(add)])
    return code

print(v_code())

猜你喜欢

转载自www.cnblogs.com/xiuyou/p/11505906.html