python(5)–random模块及验证码

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

1. random.random()      随机小数

>>> random.random()
0.6633889413427193

2. random.randint(1,9)     1-9之间随机生成一位数

>>> random.randint(1,9)
2
>>> random.randint(1,9)
2
>>> random.randint(1,9)
8
>>> random.randint(1,9)
3

3. random.randrange(1,9)       1-9之间随机生成一位数

>>> random.randrange(1, 9)
1
>>> random.randrange(1, 9)
6

验证码:

1. 生成四位数字验证码

import random

check_code = ''

for i in range(4):
current = random.randint(0, 9)
check_code = "%s%s" % (check_code, str(current)) print(check_code)

2. 生成六位数字字母的验证码

import random

check_code = ''

for i in range(6):
current = random.randint(0, 4)
if current != i:
tmp = str(chr(random.randint(65, 90))) #65-90是字母的ASCII码
else:
tmp = str(random.randint(0, 9))
check_code = "%s%s" % (check_code, tmp)
print(check_code)