二,随机函数模块的应用场景
2.生成一个验证码,需求整型0到9和字符(全大写)长度4
import random
def make_code(i):
res= ""
for j in range(i):
nmu=str(random.randint(0,9))
s=chr(random.randint(65,90))
m=random.choice([nmu,s])
res=res+m
return res
make_code(4)
print(make_code(4))
2.生成一个验证码,需求整型0到9和字符(全大写)长度4
import random
def make_code(i):
res= ""
for j in range(i):
nmu=str(random.randint(0,9))
s=chr(random.randint(65,90))
m=random.choice([nmu,s])
res=res+m
return res
make_code(4)
print(make_code(4))
字母=chr数字
数字str=字符串
数字str=字符串
3.需求:产生指定位数的验证码
第一种方法
import random
def make_code(count):
code=''
for i in range(count):
num=random.choice([1,2,3])
if num==1:
code+=str(random.randrange(0,9))
elif num==2:
code+=chr(random.randint(65,90))
else:
code+=chr(random.randint(97,122))
return code
print(make_code(4))
第二种方法
import random
def make_code(count):
code='abcdeFGHIJ0123456789'
code_list=random.sample(code,count)
return "".join(code_list)
print(make_code(4))
import random
def make_code(count):
code='abcdeFGHIJ0123456789'
code_list=random.sample(code,count)
return "".join(code_list)
print(make_code(4))