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
添加回答
举报