一、random函数简介
random()方法返回随机生成的一个实数,它在[0,1)范围内
注解:[0,1) 包括 0-1的所有实数,包含0但是不包含1
二、random()方法的语法
import random
random.random()
注意:random()是不能直接访问的,需要导入random模块,然后通过random静态对象调用该方法
三、方法讲解
1、方法:random.random()
注解:用于生成一个0到1的随机浮点数:0 <= n < 1.0
2、方法:random.randint(1,7)
注解:函数原型为:random.randint(a,b)用于生成一个指定范围内的整数
3、方法:random.randrange()
注解:
(1)函数原型为:random.randrange([start],stop[,step])
(2)从指定范围内,按指定基数递增的集合中获取一个随机数,如random.randrange(10,100,2)
结果相当于获取10,100内以步长为2的随机数,即从[10,12,14,16,…96,98]序列中获取一个随机数
(3)random.randrange(10,100,2)的结果与random.choice(range(10,100,2))等效
4、方法:random.choice()
注解:
(1)函数原型为:random.choice(sequence),参数sequence表示一个有序类型
(2)sequence在python中不是一种特定的类型,而是泛指一系列的类型
(3)list,tuple,字符串都属于sequence
(4)含义:在固定的字符串或者元组中随机获取其中的一个元素
例子:
print(random.choice("学习Python"))#学
print(random.choice(["JGood","is","a","handsome","boy"])) #List
print(random.choice(("Tuple","List","Dict"))) #List
5、方法:random.sample()
注解:
(1)函数原型为:random.sample(sequence,k)
(2)含义:从指定的序列中随机获取指定长度的片段
例子:
print(random.sample([1,2,3,4,5],3)) #[1, 2, 5]
四、实例:
1、随机整数
print( random.randint(0,99)) #70
2、随机选取0到100区间的偶数
print(random.randrange(0, 101, 2)) #4
3、随机浮点数
print( random.random()) #0.2746445568079129
print(random.uniform(1, 10)) #9.887001463194844
4、随机字符
print(random.choice('abcdefg&#%^*f')) #f
5、多个字符中选取特定数量的字符
print(random.sample('abcdefghij',3)) #['f', 'h', 'd']
6、随机选择字符串
print( random.choice ( ['apple', 'pear', 'peach', 'orange', 'lemon'] )) #apple
7、洗牌功能
items = [1,2,3,4,5,6,7]
print(items) #[1, 2, 3, 4, 5, 6, 7]
random.shuffle(items)
print(items) #[1, 4, 7, 2, 5, 3, 6]
五、生成随机验证码
1、定义一个随机数变量,然后固定验证码的位数,这里指定验证码的位数为4位数
import random check_code = '' for i in range(4): check_code += str(i) print(check_code) 结果:0123
2、由于验证码是随机的不能一直是固定的几个数字,所以我们下面采用随机数生成方法
import random check_code = '' for i in range(4): current = random.randint(1,9) check_code += str(current) print(check_code) 结果:生成了随机的4位数字的功能
3、但是我们的验证码一般是字母加数字
import random check_code = '' for i in range(4): current = random.randrange(0,4) if current == i: #如果获取的current随机数与i相同的话就获取一个字母 tmp = chr(random.randint(65,90)) #把数字对应的ascc打印出来,括号中输入数字转换成字母 else: tmp = random.randint(0,9) #如果获取的current随机数与i不相等的话就获取数字 check_code += str(tmp) print(check_code)
完整代码:
import random check_code = '' for i in range(4): current = random.randrange(0,4) if current == i: tmp = chr(random.randint(65,90)) else: tmp = random.randint(0,9) check_code += str(tmp) print(check_code)