python random简单实用示例

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值