Python之random模块

import random

print(random.random())#(0,1)之间的浮点数

print(random.randint(1,4))#[1,4]之间的整数

print(random.randrange(1,4))#[1,4)之间的数

print(random.choice([1,'a',[1,4,5,3,7],9]))#在数列里随机选一个

res=[1,'a',[1,4,5,3,7],9]

print(random.sample(res,3))#在数列里随机选3个

print(random.shuffle(res))#打乱res的顺序

实例:生成随机验证码

import random


def make_code():
    while True:
        n = input('please input number>>>').strip()
        if n == 'q': break
        if not n.isdigit(): continue
        n = int(n)
        res = ''
        for i in range(n):
            s1 = chr(random.randint(65, 90))
            s2 = str(random.randint(0, 10))
            s3 = chr(random.randint(97, 122))
            res += random.choice([s1, s2, s3])
        print(res)


make_code()
原文地址:https://www.cnblogs.com/qiaoqianshitou/p/8745355.html