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,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('pwds.txt','w')
    fw.writelines(pwds)
else:
    print('你輸入的不是數字')

 


運行結果如下:

生成密碼txt文件內容:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM