python--random模块(产生随机值)、洗牌、验证码应用

本文介绍了Python的random模块,用于生成随机数。包括random.random()、random.uniform()、random.randint()、random.randrange()等函数的用法。还探讨了random模块在实践中的应用,如洗牌操作(random.shuffle())、生成随机数字验证码、字母验证码以及混合验证码的方法。通过这些示例,展示了random模块在各种场景下的灵活性和实用性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言:
在python中用于生成随机数的模块是random,在使用前需要import

  • random.random():生成一个0-1之间的随机浮点数.
  • random.uniform(a, b):生成[a,b]之间的浮点数.
  • random.randint(a, b):生成[a,b]之间的整数.
  • random.randrange(a, b, step):在指定的集合[a,b)中,以step为基数随机取一个数.如random.randrange(0, 20, 2),相当于从[0,2,4,6,…,18]中随机取一个.
  • random.choice(sequence):从特定序列中随机取一个元素,这里的序列可以是字符串,列表,元组等,例:
    string = 'nice to meet you'
    tup = ('nice', 'to', 'meet', 'you')
    lst = ['nice', 'to', 'meet', 'you']
    print random.choice(string)
    print random.choice(tup)
    print random.choice(lst)
  • random.shuffle(lst):将列表中的元素打乱,洗牌
  • random.sample(sequence,k):从指定序列在随机抽取定长序列,原始序列不变
    string2 = 'nice to meet you'
    lst3 = ['nice', 'to', 'meet', 'you']
    print random.sample(string2, 2)
    print random.sample(lst3, 2)

应用一**洗牌:

import random
lst2 = ['nice', 'to', 'meet', 'you']
# 直接print,会返回为空
# print random.shuffle(lst2)
random.shuffle(lst2)
print lst2
输出结果为:
['you', 'meet', 'nice', 'to']

应用二**生成随机的4位数字验证码:

import random
auth = ''
for i in range(0, 4):
    current_code = random.randint(0, 9)
    auth += str(current_code)
print auth

应用三**生成随机的4位字母验证码:

auth2 = ''
for ii in range(0, 4):
    current_code = random.randint(65, 90)
    # ord()函数主要用来返回对应字符的ascii码,
    # chr()主要用来表示ascii码对应的字符他的输入时数字
    auth2 += chr(current_code)
print auth2

应用四**生成随机的4位字母、数字验证码:

auth3 = ''
for j in range(0, 4):
    current = random.randint(0, 4)
    if j == current:
        current_code = random.randint(0, 9)
    else:
        current_code = chr(random.randint(65, 90))
    auth3 += str(current_code)
print auth3
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值