python random模块

发布时间:2018-03-01 19:26:38编辑:admin阅读(3134)

    random() 方法返回随机生成的一个实数,它在[0,1)范围内。


    random()

    生成一个0到1的随机符点数

    import random
    print(random.random())

    执行输出

    0.7950347424262036


    randint()

    用于生成一个指定范围内的整数

    print(random.randint(1,7))

    执行输出 2


    randrange()

    从指定范围内,按指定基数递增的集合中 获取一个随机数

    print(random.randrange(1,3))

    执行输出 2


    choice()

    从序列中获取一个随机元素

    字符串,列表,元组都是序列

    print(random.choice('abcd'))

    执行输出 c


    sample()

    从指定序列中随机获取指定长度的片断

    print(random.sample('abcd',2))

    执行输出 ['c', 'b']


    uniform()

    指定范围内获取随机浮点数

    print(random.uniform(1,10))


    shuffle()

    洗牌,它会改变原有的值

    items = [1,2,3,4,5,6,7]
    print(items)
    random.shuffle(items)
    print(items)

    执行输出

    [1, 2, 3, 4, 5, 6, 7]

    [7, 1, 5, 2, 3, 4, 6]


    生成随机验证码:

    首先生成4位数字

    import random
    checkcode = ''
    for i in range(4):
        #执行4次,每次依次输出0,1,2,3
        checkcode += str(i)
    
    print(checkcode)

    执行输出

    0123


    生成4位随机值

    import random
    checkcode = ''
    for i in range(4):
        current = random.randrange(0, 9)
        checkcode += str(current)
    
    print(checkcode)

    执行输出

    7118


    验证码一般是数字和字母的组合,上面的代码只是实现了随机的数字

    那么就需要也能输出字母的功能

    下面先来一个功能,能够随机判断输出的是字母还是数字

    随机输出一个0~4的数字和range()输出的数字,去比较。猜对了,就是字母,否则是数字

    import random
    checkcode = ''
    for i in range(4):
        current = random.randrange(0,4)
        if i == current:
            print("字母")
        else:
            print("数字")

    执行输出

    字母

    数字

    字母

    字母


    如何随机输出字母呢?

    在ASCII码中,65~90表示A-Z的大写字母,使用chr()方法就可以获取

    print(chr(65))

    输出 A


    那么最终代码如下:

    import random
    checkcode = ''
    for i in range(4):
        current = random.randrange(0,4)
        if current != i:
            temp = chr(random.randint(65,90))
        else:
            temp = random.randint(0,9)
        checkcode += str(temp)
    print (checkcode)

    执行输出

    03RF



关键字

上一篇: python time与datetime模块

下一篇: python os模块