python3.6内置模块——random详解

python内置模块random是用来生成随机数的,在许多场合都能应用到,算是比较常见的一种模块吧,下面详细介绍其具体用法。

基本用法

  • 随机生成浮点数:有两种,一种没有参数,默认是0~1,另一种可以指定随机生成的浮点数范围。
>>> random.random()
0.6448965915384378
>>> random.uniform(5,6)
5.1662895382835075
  • 随机生成指定范围的整数:有两种方法,第二种除了可以指定范围,还可以指定步长。
>>> random.randint(1,10)
5
>>> random.randrange(1,10)
6
>>> random.randrange(1,10,2)
1
  • 随机生成指定样式中的元素:样式可以是字符串、元组、列表。
random.choice((1,2,'a','b'))
2
>>> random.choice([1,2,3,4])
1
>>> random.choice("qwerty")
't'
  • 随机生成指定数目的指定样式中的元素:样式可以是字符串、元组、列表、集合。
>>> random.sample("abcedf",2)
['c', 'e']
>>> random.sample((1,2,8,5,6),3)
[6, 5, 2]
>>> random.sample(['a','b','c','d','f'],2)
['f', 'd']
>>> random.sample({1,2,3,4,5},3)
[2, 4, 3]
>>> 
  • 将列表的元素的顺序打乱:类似于生活中的洗牌,此方法返回值为空,将改变原来列表。
>>> item = [1,2,3,4,5,6,7]
>>> random.shuffle(item)
>>> print(item)
[3, 6, 4, 2, 7, 1, 5]

简单实际应用

  • 随机生成六位数字验证码
import random

def func():
    captcha = ''
    for i in range(6):
        num = random.randint(0,9)
        captcha += str(num)
    return captcha
captcha = func()
print(captcha)
648215
  • 随机生成六位数字和区分大小写字母混合的验证码

这里我们要知道一点的是,在国际标准ASCII码中规定了字符A~Z的ASCII值为65~90,a~z的ASCII值为97~122。python内置方法chr可以将对应的ASCII值转换成对应的字符。

import random

def func():
    captcha = ''
    for i in range(6):
        a = random.randint(1,3)
        if a == 1:
            num = random.randint(0,9)
            captcha += str(num)
        elif a == 2:
            num = random.randint(65,90)
            captcha += str(chr(num))
        elif a == 3:
            num = random.randint(97, 122)
            captcha += str(chr(num))
    return captcha
captcha = func()
print(captcha)
qLK77Y