Python3.5内置模块之random模块用法实例分析

yipeiwu_com6年前Python基础

本文实例讲述了Python3.5内置模块之random模块用法。分享给大家供大家参考,具体如下:

1、random模块基础的方法

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:ZhengzhengLiu
import random
print(random.random())     #随机产生[0,1)之间的浮点值
print(random.randint(1,6))   #随机生成指定范围[a,b]的整数
print(random.randrange(1,3))  #随机生成指定范围[a,b)的整数
print(random.randrange(0,101,2)) ##随机生成指定范围[a,b)的指定步长的数(2--偶数)
print(random.choice("hello")) #随机生成指定字符串中的元素
print(random.choice([1,2,3,4])) #随机生成指定列表中的元素
print(random.choice(("abc","123","liu"))) #随机生成指定元组中的元素
print(random.sample("hello",3))  #随机生成指定序列中的指定个数的元素
print(random.uniform(1,10))   #随机生成指定区间的浮点数
#洗牌
items = [1,2,3,4,5,6,7,8,9,0]
print("洗牌前:",items)
random.shuffle(items)
print("洗牌后:",items)

运行结果:

0.1894544287915626
2
1
74
l
2
liu
['l', 'h', 'o']
1.2919229440123967
洗牌前: [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
洗牌后: [6, 9, 2, 7, 1, 3, 8, 5, 4, 0]

2、random模块中方法的实际应用——生成随机验证码

(1)随机生成4位纯数字验证码

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:ZhengzhengLiu
import random
check_code = ''  #最终生成的验证码
for i in range(4):    #4位长的纯数字验证码
  cur = random.randint(0,9)
  check_code += str(cur)
print(check_code)

运行结果:

0671

(2)随机生成4位字符串验证码(数字与字符都有)

import random
check_code = ''
for i in range(4):
  cur = random.randrange(0,4)  #随机猜的范围,与循环次数相等
  #字母
  if cur == i:
    tmp = chr(random.randint(65,90))  #随机取一个字母
  #数字
  else:
    tmp = random.randint(0,9)
  check_code += str(tmp)
print(check_code)

运行结果:

39HN

PS:这里再提供几款相关工具供大家参考使用:

在线随机数生成工具:
http://tools.jb51.net/aideddesign/rnd_num

在线随机生成个人信息数据工具:
http://tools.jb51.net/aideddesign/rnd_userinfo

在线随机字符/随机密码生成工具:
http://tools.jb51.net/aideddesign/rnd_password

在线随机数字/字符串生成工具:
http://tools.jb51.net/aideddesign/suijishu

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python数学运算技巧总结》、《Python字符串操作技巧汇总》、《Python编码操作技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

希望本文所述对大家Python程序设计有所帮助。

相关文章

python中时间转换datetime和pd.to_datetime详析

python中时间转换datetime和pd.to_datetime详析

前言 我们在python对数据进行操作时,经常会选取某一时间段的数据进行分析。这里为大家介绍两个我经常用到的用来选取某一时间段数据的函数:datetime( )和pd.to_dateti...

在Python中使用M2Crypto模块实现AES加密的教程

 AES(英文:Advanced Encryption Standard,中文:高级加密标准),是一种区块加密标准。AES将原始数据分成多个4×4字节矩阵来处理,通过预先定义的...

Python3使用PyQt5制作简单的画板/手写板实例

Python3使用PyQt5制作简单的画板/手写板实例

1.前言 版本:Python3.6.1 + PyQt5 写一个程序的时候需要用到画板/手写板,只需要最简单的那种。原以为网上到处都是,结果找了好几天,都没有找到想要的结果。 网上的要么是...

python中合并两个文本文件并按照姓名首字母排序的例子

前段时间前在网上看到一段面试题,要求如下: employee文件中记录了工号和姓名复制代码 代码如下:    cat employee.txt: ...

Python urlopen()函数 示例分享

好了,废话少说,我们先看看几个示例吧 一、打开一个网页获取所有的内容 复制代码 代码如下:from urllib import urlopendoc = urlopen("http://...