1、取随机小数
import random print(random.random()) # (0,1) print(random.uniform(2,3)) # (n,m)
2、取随机整数
import random print(random.randint(1,2)) # [1,2] print(random.randrange(1,2)) # [1,2) print(random.randrange(1,100,2)) # 取随机奇数
3、从一个类表中随机抽取
import random lst = [1,2,3,4,5,('a','b'),'ss','dd'] ret = random.choice(lst) print(ret)
3.2在range中使用
import random ret1 = random.choice(range(100)) print(ret1)
3.3在列表中取3个值
import random lst = [1,2,3,4,5,('a','b'),'ss','dd'] ret11= random.sample(lst,3) # sample print(ret11)
4、乱序:元素随机排序
import random lst = [1,2,3,4,5,('a','b'),'ss','dd'] random.shuffle(lst) print(lst) # ['dd', 3, 1, 4, 5, ('a', 'b'), 2, 'ss']
5、random的应用 验证码
import random def get_code(n=6): code = '' for i in range(n): num = random.randint(0,9) code += str(num) return code ret = get_code() print(ret)
6、random的应用 带大、小写字母和数字的验证码
import random def get_code(n): code = '' for i in range(n): num = str(random.randint(0,9)) alpha_upper = chr(random.randint(65,90)) alpha_lower = chr(random.randint(97,122)) c = random.choice([num ,alpha_upper,alpha_lower]) code +=c return code ret = get_code(6) print(ret)