python⼏种⽅法实现随机⽣成8位同时包含数字、⼤写字符、⼩
写字符密码的⼩程序
python 实现随机⽣成包8位包含⼤写字母、⼩写字母和数字的密码的程序。
要求:
1⽤户输⼊多少次就⽣成多少条密码,
2要求密码必须同时包含⼤写字母、⼩写字母和数字,长度8位,不能重复
代码如下:
import string, random
src_upp = string.ascii_uppercase
src_let = string.ascii_lowercase
src_num = string.digits
lis = []
count = input('请输⼊次数:').strip()
# for 循环实现(产⽣密码数可能不⾜)
for i in range(int(count)):
print(i)
# 先随机定义3种类型各⾃的个数(总数为8)
upp_c = random.randint(1, 6)
low_c = random.randint(1, 8-upp_c - 1)
num_c = 8 - (upp_c + low_c)
# 随机⽣成密码
password = random.sample(src_upp, upp_c)+random.sample(src_let, low_c)+random.sample(src_num, num_c)
# 打乱列表元素
random.shuffle(password)
# 列表转换为字符串
new_password = ''.join(password)+'\n'
if new_password not in lis:
lis.append(new_password)
with open('', 'w') as fw:
fw.seek(0)
fw.writelines(lis)
fw.close()
# while 循环实现(只有密码不重复才+1)
j=0
while j< int(count):
print(j)
upp_c = random.randint(1, 6)
low_c = random.randint(1, 8 - upp_c - 1)
num_c = 8 - (upp_c + low_c)
# 随机⽣成密码
password = random.sample(src_upp, upp_c) + random.sample(src_let, low_c) + random.sample(src_num, num_c)
# 打乱列表元素
random.shuffle(password)
# 列表转换为字符串
new_password = ''.join(password) + '\n'
if new_password not in lis:
lis.append(new_password)
j += 1
with open('', 'w') as fw:
fw.seek(0)
fw.writelines(lis)
fw.close()
# ⽤集合交集的⽅法⽣成密码:
import random,string
num = input('请输⼊⼀个数字:').strip()
pwds = set()
if num.isdigit():
while len(pwds)<int(num): # 保证⽣成条数⾜够
passwd = set(random.sample(string.ascii_letters+string.digits,8))
set1 = set(string.ascii_uppercase).intersection(passwd)
set2 = set(string.ascii_lowercase).intersection(passwd)
set3 = set(string.digits).intersection(passwd)
if set1 and set2 and set3:
str_passwd=''.join(passwd)+'\n'#要把产⽣的密码变成字符串,因为前⾯已经给变成集合了
pwds.add(str_passwd)
fw =open('','w')
fw.writelines(pwds)
else:
print('你输⼊的不是数字')
运⾏结果如下:
密码字符串是什么
⽣成密码txt⽂件内容:

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。