python 几种方法实现随机生成8位同时包含数字、大写字符、小写字符密码的小程序

时间:2023-03-09 15:37:12
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('password.txt', '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('password.txt', '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,))
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('pwds.txt','w')
fw.writelines(pwds)
else:
print('你输入的不是数字')
运行结果如下:

python 几种方法实现随机生成8位同时包含数字、大写字符、小写字符密码的小程序

生成密码txt文件内容:

python 几种方法实现随机生成8位同时包含数字、大写字符、小写字符密码的小程序