python -- random模块

python -- random模块

  • random.random(),随机(0,1)的浮点数,返回类型:float
  • random.ranint(int1,int2),随机从int1到int2的整数,返回类型:int
  • random.randrange(int1,int2),随机从int1到int2的整数,但是不包含int2,range是顾头不顾尾。返回类型:int
  • random.choice(有序类型),序列类型有字符串,列表,元组。字典和int不可用。返回类型:str,int
  • random.sample(序列,步长),对序列进行步长值得随机,返回类型:列表
  • random.uniform(int1,int2),随机从int1到int2的浮点数,返回类型:float
  • random.shuffle(list),将原list序列重新排列,并返回list,此时list的内存地址不变。

random模块的案例:验证码

import random

codelist = ['a', 'b', 'c', 'd']
checkcode = ''

for i in range(3):
    current_num = random.randint(1,9)
    current_let = random.choice(codelist)
    checkcode += str(current_num)
    checkcode += str(current_let)

print(checkcode)

高逼格版

import random

checkcode = ''
'''用chr()找到ascii表中对应的关系,数字-->字母'''
'''ascii(65,90),大写字母(97,122),小写字母'''
for i in range(4):
    current = random.randrange(0, 4)
# current与i相匹配,就用大写字母
    if current == i:
        tmp = chr(random.randint(65, 90))
# current大于i,就用小写字母
    elif current > i:
        tmp = chr(random.randint(97, 122))
# current小于i,就用数字
    else:
        tmp = random.randint(0, 9)
    checkcode += str(tmp)

print(checkcode)

写在后面

random 作用 返回值类型 备注
random.random() 随机从(0,1)取 float ()内不加参数
random.uniform(int1,int2) 随机从int1到int2中取 float random.random()的升级版
random.randrange(int1,int2) 随机从int1到int2取 int 顾头不顾尾,不包含int2
random.choice() 将有序类型随机一个元素 int/str int和dirc无法序列
random.sample(序列,步长) 将有序类型随机c出一个列表,列表长度=步长 list int和dirc无法序列
random.shuffle(list) 重新排列list顺序 无返回值 将原list内存地址的顺序打乱
posted @ 2017-07-19 18:08  gzz041  阅读(199)  评论(0编辑  收藏  举报