码迷,mamicode.com
首页 > 其他好文 > 详细

random模块

时间:2018-08-10 21:34:15      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:code   1.9   nbsp   amp   style   shuffle   choice   验证   bsp   

random模块是用于获取随机数的模块

导入:

import random.random

关于使用:

import random
 
print(random.random())    # (0,1),取0到1的开区间中的浮点数
 
print(random.randint(1,3))  # [1,3],取1到3的闭区间的整数
 
print(random.randrange(1,3)) # [1,3),取1到3的左闭右开区间的整数
 
print(random.choice([1,23,[4,5]]))  # 23,从一个可迭代对象中随机选取一个元素
 
print(random.sample([1,23,[4,5]],2))  # [[4, 5], ‘23‘],从可迭代对象中随机选取元素,第二个参数为要选取几个参数
 
print(random.uniform(1,3))  #1.927109612082716,获取指定范围内的浮点数,范围为开区间。
 
item=[1,3,5,7,9]
random.shuffle(item)    # 将原有的列表中的元素顺序打乱。
print(item)

 

例子:

技术分享图片
import random

def v_code():

    code = ‘‘
    for i in range(5):

        num=random.randint(0,9)
        alf=chr(random.randint(65,90))
        add=random.choice([num,alf])
        code += str(add)
    return code

print(v_code())
验证码

 

random模块

标签:code   1.9   nbsp   amp   style   shuffle   choice   验证   bsp   

原文地址:https://www.cnblogs.com/kuxingseng95/p/9456977.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!