random模块:
>>> import random
>>> random.random() #0到1之间的数 (0, 1);
0.16533475988055923
>>>
>>> random.randint(1,3) #1到3之前的整数 [1, 3]
1
>>>
>>> random.randint(1,3)
3
>>> random.randint(1,3)
2
>>> random.randint(1,3)
3
>>> random.randrange(1, 3) #1到3之前的整数 [1, 3)
1
>>> random.randrange(1, 3)
2
>>> random.randrange(1, 3)
1
>>> random.randrange(1, 3)
1
>>>
>>> import random
>>> random.random() #0到1之间的数 (0, 1);
0.16533475988055923
>>>
>>> random.randint(1,3) #1到3之前的整数 [1, 3]
1
>>>
>>> random.randint(1,3)
3
>>> random.randint(1,3)
2
>>> random.randint(1,3)
3
>>> random.randrange(1, 3) #1到3之前的整数 [1, 3)
1
>>> random.randrange(1, 3)
2
>>> random.randrange(1, 3)
1
>>> random.randrange(1, 3)
1
>>>
1. 随机选取字符串
>>> random.choice("hello") 参数需要是序列,字符串,元组,列表。
'l'
2. 多个字符串选取特定数量的字符
>>> random.sample("asasas", 2) #指定长度取,从字符串中随机取2位
['a', 'a']
>>> random.choice("hello") 参数需要是序列,字符串,元组,列表。
'l'
2. 多个字符串选取特定数量的字符
>>> random.sample("asasas", 2) #指定长度取,从字符串中随机取2位
['a', 'a']
>>> random.uniform(1,3)
1.1422713831096774
>>> random.uniform(1,3)
2.043928712313657
>>> random.uniform(1,3)
2.1317285111885793
>>> random.uniform(1,3)
2.106939191769194
>>>
random.shuffle #洗牌功能:
>>> a = [1,2,3,4,5,6,7]
>>> random.shuffle(a)
>>> a
[2, 7, 4, 1, 5, 6, 3]
>>> random.shuffle(a)
>>> a
[3, 7, 5, 4, 2, 1, 6]
>>>
生成随机验证码:
import random
check_code = ""
for i in range(6):
current = random.randrange(0, 6)
if i == current:
check_code += chr(random.randint(65, 90))
else:
check_code += str(random.randint(0, 9))
print(check_code)
>>> a = [1,2,3,4,5,6,7]
>>> random.shuffle(a)
>>> a
[2, 7, 4, 1, 5, 6, 3]
>>> random.shuffle(a)
>>> a
[3, 7, 5, 4, 2, 1, 6]
>>>
生成随机验证码:
import random
check_code = ""
for i in range(6):
current = random.randrange(0, 6)
if i == current:
check_code += chr(random.randint(65, 90))
else:
check_code += str(random.randint(0, 9))
print(check_code)