Python基础 之 Python random 模块 2

简介: Python random 模块

Python基础 之 Python random 模块 2

Python random 模块

Python random 模块主要用于生成随机数。

random 模块实现了各种分布的伪随机数生成器。

要使用 random 函数必须先导入:

import random

查看 random 模块中的内容:

实例

import random
dir(random)
['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random', 'SG_MAGICCONST', 'SystemRandom', 'TWOPI', '_Sequence', '_Set', 'all', 'builtins', 'cached', 'doc', 'file', 'loader', 'name', 'package', 'spec', '_accumulate', '_acos', '_bisect', '_ceil', '_cos', '_e', '_exp', '_floor', '_inst', '_log', '_os', '_pi', '_random', '_repeat', '_sha512', '_sin', '_sqrt', '_test', '_test_generator', '_urandom', '_warn', 'betavariate', 'choice', 'choices', 'expovariate', 'gammavariate', 'gauss', 'getrandbits', 'getstate', 'lognormvariate', 'normalvariate', 'paretovariate', 'randbytes', 'randint', 'random', 'randrange', 'sample', 'seed', 'setstate', 'shuffle', 'triangular', 'uniform', 'vonmisesvariate', 'weibullvariate']

seed() 方法改变随机数生成器的种子,可以在调用其他随机模块函数之前调用此函数。

实例

!/usr/bin/python3

import random

random.seed()
print ("使用默认种子生成随机数:", random.random())
print ("使用默认种子生成随机数:", random.random())

random.seed(10)
print ("使用整数 10 种子生成随机数:", random.random())
random.seed(10)
print ("使用整数 10 种子生成随机数:", random.random())

random.seed("hello",2)
print ("使用字符串种子生成随机数:", random.random())

以上实例运行后输出结果为:

使用默认种子生成随机数: 0.7908102856355441
使用默认种子生成随机数: 0.81038961519195
使用整数 10 种子生成随机数: 0.5714025946899135
使用整数 10 种子生成随机数: 0.5714025946899135
使用字符串种子生成随机数: 0.3537754404730722

目录
相关文章
|
22天前
|
XML Shell API
python ConfigParser、shutil、subprocess、ElementTree模块简解
python ConfigParser、shutil、subprocess、ElementTree模块简解
|
21天前
|
存储 算法 数据库
使用python hashlib模块给明文字符串加密,以及如何撞库破解密码
`hashlib` 是 Python 中用于实现哈希功能的模块,它可以将任意长度的输入通过哈希算法转换为固定长度的输出,即散列值。该模块主要用于字符串加密,例如将用户名和密码转换为不可逆的散列值存储,从而提高安全性。`hashlib` 提供了多种哈希算法,如 `md5`、`sha1`、`sha256` 等。
34 1
|
9天前
|
Java Serverless Python
探索Python中的并发编程与`concurrent.futures`模块
探索Python中的并发编程与`concurrent.futures`模块
14 4
|
21天前
|
API Python
python ratelimit模块
python ratelimit模块
|
21天前
|
Python
像导入Python模块一样导入ipynb文件
像导入Python模块一样导入ipynb文件
|
22天前
|
Python
如何最简单、通俗地理解Python模块?
如何最简单、通俗地理解Python模块?
|
21天前
|
算法 Python
python tarfile模块
python tarfile模块
|
22天前
|
SQL 关系型数据库 MySQL
Python之MySQL操作及Paramiko模块操作
Python之MySQL操作及Paramiko模块操作
|
22天前
|
存储 JSON JavaScript
python序列化: json & pickle & shelve 模块
python序列化: json & pickle & shelve 模块
|
20天前
|
Python
如何在 Python 中导入模块
【8月更文挑战第29天】
20 1