2 回答

TA貢獻1886條經驗 獲得超2個贊
選擇“Y”后并沒有停止循環,因此未完成的函數將繼續執行。通過使用return語句(而不是break),您可以停止函數打印它生成的密碼。
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())
作為旁注,如果您實際使用它們,則不應使用默認的隨機模塊來生成密碼。使用該secrets模塊或使用隨機數生成器播種更安全
import os
import random
random.seed(os.urandom(16))
實現安全。

TA貢獻1802條經驗 獲得超4個贊
您可以添加一個標志而不是再次調用該函數(內部 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
添加回答
舉報