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

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)
posted @ 2016-03-13 22:21  黄小墨  阅读(543)  评论(0编辑  收藏  举报