16Python标准系列之random模块

简介:

Python标准库系列之random模块


This module implements pseudo-random number generators for various distributions.


random.random()

生成0-1的小数

1
2
3
4
5
6
7
8
>>> random.random()
0.06511225392331632
>>> random.random()
0.9063480964287944
>>> random.random()
0.1255900898753961
>>> random.random()
0.6676866041289258

random.randint(a, b)

输出a和b范围内的数,包括a和b

1
2
3
4
5
6
7
8
9
10
11
12
>>> random.randint( 1 , 2 )
1
>>> random.randint( 1 , 2 )
1
>>> random.randint( 1 , 2 )
1
>>> random.randint( 1 , 2 )
2
>>> random.randint( 1 , 2 )
1
>>> random.randint( 1 , 2 )
1

random.randrange(start, stop[, step])

输出start到stop-1之间的数,可设置步长

1
2
3
4
5
6
>>> random.randrange( 1 , 3 )
2
>>> random.randrange( 1 , 3 )
1
>>> random.randrange( 1 , 3 )
2

随机验证码实例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#!/usr/bin/env python
import  random
checkcode  =  ''
# for循环四次
for  in  range ( 4 ):
     # current=0-3的数字
     current  =  random.randrange( 0 , 4 )
     # 如果current的值不等于i
     if  current ! =  i:
         # 通过chr把数字转换为一个字母赋值给temp
         temp  =  chr (random.randint( 65 , 90 ))
     else :
         # 否则temp=0-9之间的数字
         temp  =  random.randint( 0 , 9 )
     # checkcode = checkcode + str(temp)
     checkcode  + =  str (temp)
# 输出字符
print (checkcode)

执行

1
2
3
4
5
6
7
8
ansheng@ansheng - me:~$ python s.py
TCQ1
ansheng@ansheng - me:~$ python s.py
8L01
ansheng@ansheng - me:~$ python s.py
N2EB
ansheng@ansheng - me:~$ python s.py









本文转自 Edenwy  51CTO博客,原文链接:http://blog.51cto.com/edeny/1925796,如需转载请自行联系原作者
目录
相关文章
|
1天前
|
JSON 数据格式 Python
Python标准库中包含了json模块,可以帮助你轻松处理JSON数据
【4月更文挑战第30天】Python的json模块简化了JSON数据与Python对象之间的转换。使用`json.dumps()`可将字典转为JSON字符串,如`{"name": "John", "age": 30, "city": "New York"}`,而`json.loads()`则能将JSON字符串转回字典。通过`json.load()`从文件读取JSON数据,`json.dump()`则用于将数据写入文件。
6 1
|
5天前
|
人工智能 安全 Java
Python 多线程编程实战:threading 模块的最佳实践
Python 多线程编程实战:threading 模块的最佳实践
122 5
|
5天前
|
人工智能 数据库 开发者
Python中的atexit模块:优雅地处理程序退出
Python中的atexit模块:优雅地处理程序退出
8 3
|
8天前
|
存储 开发者 Python
Python中的argparse模块:命令行参数解析的利器
Python中的argparse模块:命令行参数解析的利器
16 2
|
8天前
|
开发者 Python
Python的os模块详解
Python的os模块详解
16 0
|
11天前
|
数据挖掘 API 数据安全/隐私保护
python请求模块requests如何添加代理ip
python请求模块requests如何添加代理ip
|
13天前
|
测试技术 Python
Python 有趣的模块之pynupt——通过pynput控制鼠标和键盘
Python 有趣的模块之pynupt——通过pynput控制鼠标和键盘
|
13天前
|
Serverless 开发者 Python
《Python 简易速速上手小册》第3章:Python 的函数和模块(2024 最新版)
《Python 简易速速上手小册》第3章:Python 的函数和模块(2024 最新版)
42 1
|
14天前
|
开发者 Python
Python中的并发编程:使用asyncio模块实现异步任务
传统的Python编程中,使用多线程或多进程进行并发操作时,常常会面临性能瓶颈和资源竞争的问题。而随着Python 3.5版本的引入,asyncio模块为开发者提供了一种基于协程的异步编程方式。本文将介绍如何使用asyncio模块实现异步任务,提高Python程序的并发处理能力。
|
14天前
|
测试技术 Python
Python 的自动化测试:如何使用 Python 的 unittest 模块进行测试?
在Python中进行自动化测试可利用`unittest`模块。以下是一个简单的示例,展示了如何编写测试用例
10 0