python random 模块及验证码功能

时间:2023-12-12 15:57:26

random模块

import random
random.random()
random.randint(1,3) # 1-3的整数包括3
import random
print(random.random())
print(random.randint(1,20))
print(random.randrange(1,3)) # 顾头不顾尾,不包含3
print(random.choice('12345')) # 可迭代对象中随机取一个
print(random.sample('12345',2)) # 可迭代对象中随机取两个
print(random.uniform(1,10)) # 1-10的浮点数
items = [1,2,3,4,5,6,7]
random.shuffle(items) # 洗牌 打乱items的顺序
print(items)

验证码

简单 4位数字

import random
checkcode = ''
for i in range(4):
checkcode += str(random.randrange(10))
print(checkcode)

中等

import random
checkcode = ''
for i in range(4):
current = random.randrange(0,4)
if current == i:
tmp = chr(random.randint(65,90))
else:
tmp = random.randint(0,9)
checkcode+=str(tmp)
print(checkcode)