0,文档
参看官方文档: https://docs.python.org/zh-cn/3/library/random.html
该模块实现了各种分布的伪随机数生成器。
1, 生成随机数
import random
import numpy as np
resultInRange = random.randint(10, 20) # 10, 20区间的随机数
resFive = np.random.randn(5)
randomValue = random.random() #返回 [0.0, 1.0) 范围内的下一个随机浮点数
floatValue = random.uniform(1, 10)
listElem = ['剪刀', '石头', '布', 'a', 1, 5]
choiceVal1 = random.choice(listElem)
choiceVal2 = random.choice(listElem)
print("resultInRange10-20 randint:{}".format(resultInRange))
print("resFive:{}".format(resFive))
print("randomValue:{}".format(randomValue))
print("floatValue1-10:{}".format(floatValue))
print("choiceVal1:{}, choiceVal2:{}".format(choiceVal1, choiceVal2))
某次的执行结果(因为是随机数,所以结果不是每次都一样)
resultInRange10-20 randint:16
resFive:[-0.91103044 -0.68924712 0.80678581 0.50803157 -1.09224595]
randomValue:0.380402814947828
floatValue1-10:9.458468500238649
choiceVal1:5, choiceVal2:1
2, 生成密码
生成随机密码, 密码必须以字符开始,必须包括字符和数字。
import string
from random import sample, choice
import secrets
chars = string.ascii_lowercase + string.ascii_uppercase
charsAndDigits = chars + string.digits
def complex_password(length=8) -> str:
if length < 6:
raise Exception("the min length for password is 6")
pwTmp = choice(chars) + choice(string.digits)
leftPart = ''.join(sample(charsAndDigits, (length - 2)))
return pwTmp + leftPart
if __name__ == '__main__':
pw = complex_password()
print('pw={}, length={}'.format(pw, len(pw)))
pw = secrets.token_urlsafe(12)
print('using secrets module, pw={}, length={}'.format(pw, len(pw)))
pw = complex_password(5)
print('pw={}, length={}'.format(pw, len(pw)))
某次的执行结果(因为是随机数,所以结果不是每次都一样)
Traceback (most recent call last):
File "/Users/xxx/PycharmProjects/flashdemo/random_demo.py", line 26, in <module>
pw = complex_password(5)
File "/Users/xxx/PycharmProjects/flashdemo/random_demo.py", line 12, in complex_password
raise Exception("the min length for password is 6")
Exception: the min length for password is 6
pw=e3dJE6sL, length=8
using secrets module, pw=TKZaXUi2Vq9_XreG, length=16
Process finished with exit code 1