random模块
【1】随机小数
-
大于0小于1之间的小数
import random res=random.random() print(res) #0.555283910965662
-
指定区间的小数
import random res=random.uniform(1,9) print(res) #2.9961312595216087
【2】随即小数
-
随机区间整数(randint)
import random # 大于等于1且小于等于5之间的整数 res = random.randint(1, 10) print(res) # 7
-
随机区间奇偶数
import random # 随机区间奇数 (开始,结束,步长) res_one = random.randrange(1, 10, 2) print(res_one) # 5
【3】随即选择返回
-
随机返回一个(choice)
import random choice=['hope',1,3,'江苏'] res=random.choice(choice) print(res) #3
-
随机返回指定个数
import random choice=['hope',1,3,'江苏'] res=random.sample(choice,2) print(res) #[1, '江苏']
-
打乱列表顺序(shuffle)
list=[1,4,3,5,6] random.shuffle(list) print(list) #[4, 3, 1, 5, 6]
【4】生成6位随机验证码
- 数字大小写都具备的6位验证码
def fun(n):
code=''
for i in range(n):
a=str(random.randint(0,9))
b=chr(random.randint(65,90))
c=chr(random.randint(97,122))
res=random.choice([a,b,c])
code+=res
return code
print(fun(5))
#58YiW