1 # 生成随机验证码
2 # 4位数字的
3 import random
4 # 0-9
5 # 基础版本
6 # code = ''
7 # for i in range(4):
8 # num = random.randint(0,9) # 随机产生0-9
9 # code += str(num)
10 # print(code)
11 """ 函数版本""" 生成随机验证码 4位数字的
12 def rand_code():
13 code = ''
14 for i in range(4):
15 num = random.randint(0,9)
16 code += str(num)
17 return code
18
19
20 print(rand_code())
21 # 6 位 数字+字母
22 import random
23 code = ''
24 for i in range(6):
25 num = str(random.randint(0,9)) # 随机生成数字
26 alph = chr(random.randint(97,122)) # 随机产出小写字母
27 alph_upper = chr(random.randint(65,90)) # 随机产生大写字母
28 atom = random.choice([num, alph, alph_upper ])
29 code += atom
30 print(code)
31 """函数版本""" 6 位 数字+字母
32 import random
33 def rand_code():
34 code = ''
35 for i in range(6):
36 num = str(random.randint(0,9)) # 随机生成数字
37 alph = chr(random.randint(97,122)) # 随机产出小写字母
38 alph_upper = chr(random.randint(65,90)) # 随机产生大写字母
39 atom = random.choice([num, alph, alph_upper ])
40 code += atom
41 return code
42
43
44 print(rand_code())
45 """最终版本"""
46 import random
47 def rand_code(n=6, alph=True):
48 code = ''
49 for i in range(6):
50 num = str(random.randint(0,9)) # 随机生成数字
51 if alph:
52 alph = chr(random.randint(97,122)) # 随机产出小写字母
53 alph_upper = chr(random.randint(65,90)) # 随机产生大写字母
54 num = random.choice([num, alph, alph_upper ])
55 code += num
56 return code
57
58
59 print(rand_code(5, alph= False))
60
61
62
63
64
65 # ***** 永远不要创建一个和你知道的模块同名的文件名