一 概述

random模块就是取随机数的模块,主要用来做如下四件事情

  • 取随机小数 用的比较少,再并发编程中可能会用到
  • 取随机整数 用的比较多
  • 从一个列表重随机抽取值
  • 打乱一个列表的顺序

二: 随机取小数

  • random.random # 返回一个随机的小数
  • ramdom.uniform # 按照一个区间返回一个小数

2.1  random

import random      # 导入random模块
print(random.random()) # 调用random属性方法,返回值是一个小数
# 0.07819825943946712

2.2  uniform

import random  # 导入random模块
print(random.uniform(0,1)) # 随机生成一个0-1之间的小数
print(random.uniform(1,2)) # 随机生成一个1-2之间的小数

三 取随机整数

  • random.randint # 返回一个整数 闭区间取值
  • random.randrange # 返回一个整数 顾首不顾尾,也可以指定间隔
  • 例如彩票 抽奖等

3.1 randint

import random  # 导入random模块
print(random.randint(1,5)) # 随机打印一个1-5之前的整数,包括1和5

3.2 randrange

import random
print(random.randrange(1,2)) # 会一直取1 不包括2
print(random.randrange(1,100,2)) # 再1到100中取间隔为2的整数,不包括100

四: 从一个列表中随机取值

  • random.choice  # 从中选择一个元素返回,多次choice可能取到同一个值
  • random.sample # 从中选择多个元素返回 ,取到的多个值不可能重复

4.1 choice

import random
l = ['wangys',18,(1,2)]
print(random.choice(l))

4.2 sample

import random
l = ['wangys',18,(1,2)]
print(random.sample(l,2))

五: 打乱一个列表的顺序

打乱原列表的顺序,并不会产生一个新的列表

例如字牌,麻将游戏洗牌等

5.1 shuffle

import random  # 导入random模块
l = [1,2,3,4,5] # 定义一个l列表
random.shuffle(l) # 打乱顺序
print(l) # 查看已经打乱顺序的列表

六: 练习题

6.1  生成一个随机验证码

需求:

  • 一个随机验证码
  • 可以进行选择是纯数字还是字母数字组合
  • 可以选择位数
  • 默认6位
import random
def createIdentifyingCode(n = 6,alpha = True):
s = ''
for i in range(n):
res = str(random.randint(0,9))
if alpha:
alpha_upper = chr(random.randint(65,90))
alpha_lower = chr(random.randint(97,122))
res = random.choice([res,alpha_lower,alpha_upper])
s += res
return s
print(createIdentifyingCode())
print(createIdentifyingCode(alpha=False))

6.2 发红包

  • 拼手气红包
  • 用户输入金额和红包数量
  • 要注意每个人抢到红包的几率是一样的

最新文章

  1. Dev Express 动态生成XRTable使用总结
  2. visual studio 查找/替换对话框
  3. BCG界面库下的Windows8 UI界面样式www.webui8.com
  4. ng-click
  5. 菜鸟学习Hibernate——一对多关系映射
  6. 实例学习Bloom Filter
  7. Python Tutorial 学习(十)-- Brief Tour of the Standard Library
  8. Android UI 调试常用工具(Dump view UI hierarchy for Automator)
  9. JAVA函数的参数传递
  10. JavaScript Function.arguments 属性详解
  11. 【BZOJ 4652】【NOI 2016】循环之美
  12. Oracle:WITH AS () Merge ?
  13. 显示等待 (web自动化测试)
  14. 高精度加法——经典题 洛谷p1601
  15. python--继承关系
  16. Codeforces 605C Freelancer's Dreams 凸包 (看题解)
  17. CodeForces700E Cool Slogans
  18. shell脚本read -t 超时输入测试
  19. 基于tcpdump的Android智能移动终端数据包捕获完整解决方案
  20. session hijacking-php.ini

热门文章

  1. html超文本标记语言基础一
  2. CF1110D Jongmah
  3. Jquery的一些常见用法
  4. .net中的设计模式---单例模式
  5. BIM平台 http://gzcd.bim001.cn
  6. ABP后台服务之作业调度Quartz.NET
  7. Html input 常见问题
  8. 范围for语句
  9. Gitbook
  10. LabVIEW版本控制(转)