Day5模块-random模块

random:随机数

>>> import random
>>> print(random.random()) #生成随机小数
0.6906362176182085

>>> print(random.randint(1,5)) #生成1-5的随机数,包括5
1

>>> print(random.sample(range(100),5))  #从0-100随机生成5个
[42, 0, 15, 83, 20]

两个实例:随机验证码

 1 >>> import string
 2 >>> import random
 3 >>> print(string.ascii_letters)  #ascii码所有的字母,包含大小写
 4 abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
 5 >>> print(string.digits) #数字
 6 0123456789
 7 >>>
 8 >>> str_source = string.ascii_letters + string.digits
 9 #随机挑选其中6位
10 >>> print(random.sample(str_source,6))
11 ['C', 'y', 'N', 'j', 'o', '9']
12 #字符串拼接下,生成6位随机数
13 >>> print(''.join(random.sample(str_source,6)))
14 UXMqa3
View Code
 1 import random
 2 
 3 checkcode = ''
 4 for i in range(4):
 5     current = random.randrange(0,4) #生成0-3的随机数
 6     if current != i: #判断是否等于当前随机数
 7         temp = chr(random.randint(65,90)) #随机A-Z的字母
 8     else:
 9         temp = random.randint(0,9) #0-9的随机数
10     checkcode += str(temp) #拼接起来
11 print(checkcode)
12 
13 另:该例子是银角大王的例子
14 chr(65) 
15 'A'
16 chr(90)
17 'Z'
View Code
原文地址:https://www.cnblogs.com/wolfs685/p/6886280.html