2 回答

TA貢獻(xiàn)1886條經(jīng)驗(yàn) 獲得超2個(gè)贊
選擇“Y”后并沒(méi)有停止循環(huán),因此未完成的函數(shù)將繼續(xù)執(zhí)行。通過(guò)使用return語(yǔ)句(而不是break),您可以停止函數(shù)打印它生成的密碼。
import random
from string import ascii_lowercase, ascii_uppercase, digits
special_chars = "!#$%&*@^"
available_chars = list(ascii_lowercase) + list(ascii_uppercase) + list(digits) + list(special_chars)
def get_length():
user_l = ""
while not user_l.isdigit() or int(user_l) < 6:
user_l = input("Please input a password length.\n")
return int(user_l)
print(int(user_l))
def pwd_gen(length):
return [random.choice(available_chars) for i in range(length)]
def pwd_chk(length):
pwd = []
while True:
pwd = pwd_gen(length)
if set(pwd) & set(ascii_lowercase) == set():
continue
elif set(pwd) & set(ascii_uppercase) == set():
continue
elif set(pwd) & set(digits) == set():
continue
elif set(pwd) & set(special_chars) == set():
continue
else:
print("\nYour password is " + "".join(pwd))
while True:
accept = input("Would you like a different password? Y/N\n\n")
if accept.lower() == "n" or accept.lower() == "no":
print("\nYour password is:")
break
elif accept.lower() == "y" or accept.lower() == "yes":
pwd_chk(length)
return # CHANGE THIS FROM "break" TO "return"! #
else:
print("\nInvalid input. Your password is " + "".join(pwd))
continue
break
pwd = "".join(pwd)
print(pwd)
pwd_chk(get_length())
作為旁注,如果您實(shí)際使用它們,則不應(yīng)使用默認(rèn)的隨機(jī)模塊來(lái)生成密碼。使用該secrets模塊或使用隨機(jī)數(shù)生成器播種更安全
import os
import random
random.seed(os.urandom(16))
實(shí)現(xiàn)安全。

TA貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超4個(gè)贊
您可以添加一個(gè)標(biāo)志而不是再次調(diào)用該函數(shù)(內(nèi)部 while 代碼):
while True:
replace_password = False # Flag added here
accept = input("Would you like a different password? Y/N\n\n")
if accept.lower() == "n" or accept.lower() == "no":
print("\nYour password is:")
break
elif accept.lower() == "y" or accept.lower() == "yes":
replace_password = True # Setting flag
break
else:
print("\nInvalid input. Your password is " + "".join(pwd))
continue
if replace_password: # Action based on flag
continue
break
添加回答
舉報(bào)