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中取floatrandom.random()的升级版
random.randrange(int1,int2)随机从int1到int2取int顾头不顾尾,不包含int2
random.choice()将有序类型随机一个元素int/strint和dirc无法序列
random.sample(序列,步长)将有序类型随机c出一个列表,列表长度=步长listint和dirc无法序列
random.shuffle(list)重新排列list顺序无返回值将原list内存地址的顺序打乱

转载于:https://www.cnblogs.com/gzz041/p/7207161.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值