Python random模块

random 模块用于生成随机数

import random

print(random.random())              # 生成[0, 1)内一个随机的浮点数

print(random.uniform(0, 1.2))       # 生成[0, 1.2)内一个随机的浮点数

print(random.randint(1, 3))         # 生成[1, 3]内一个随机的整数

print(random.randrange(1, 10))      # 生成[1, 10)内一个随机的整数

print(random.choice('random'))      # 随机挑选一个字符

print(random.sample('random', 2))   # 随机挑选两个字符

items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
random.shuffle(items)               # 打乱顺序
print(items)

输出结果:

0.26269044748244874
0.4141990468958614
3
3
o
['a', 'd']
[4, 8, 1, 9, 6, 2, 7, 5, 0, 3]

 

示例:

import random

check_code = ''                                 # 初始化验证码字符串
for i in range(6):                              # 6位验证码,循环6次
    c = random.randint(0, 1)                    # 数字,大写字母随机随机出现
    if c:
        tem = chr(random.randint(65, 90))       # 如果c=1,出现一个随机的大写字母(ASCII)
    else:
        tem = random.randint(0, 9)              # 如果c=0,出现一个随机的数字
    check_code += str(tem)                      # 将新的验证码加到后面
print(check_code)

输出结果:

PE8RJ9

posted on 2019-03-22 10:16  doubtful  阅读(195)  评论(0编辑  收藏  举报

导航