Python密码验证循环无法终止问题求助
问题解决:密码验证后循环无法终止的问题
问题根源
你的代码存在两个关键问题,导致验证通过后循环不终止且错误提示逻辑混乱:
- 找到匹配密码后,仅跳出了遍历文件行的内层
for循环,但外层的while True循环没有被终止,程序会持续要求输入密码。 - 错误提示的判断放在了
for循环内部,文件中每一行不匹配密码时都会打印一次错误信息,而非遍历完整文件、确认无匹配后才提示错误。
修正后的代码
my_list = ["yes", "no"] while True: password_question: str = input('Do you want to create a new password?, please type yes or no ') word = password_question if word.lower() in my_list: break else: print("Sorry, try again") if password_question.lower() == my_list[0]: # 兼容大小写输入 print("Great, let's get started!") # 用with语句自动管理文件关闭,避免资源泄漏 with open("passwords.txt", "a") as text_write: new_password = input("Please enter a new password -> ") text_write.write(new_password + '\n') print("Okay, your new password is " + new_password) while True: password: str = input("Please enter your password -> ") found: bool = False with open("passwords.txt", "r") as text_read: for line in text_read: if line.rstrip() == password: print("Great, you are logged in!") found = True break # 跳出遍历文件的内层循环 # 遍历完整个文件后再判断结果 if found: break # 跳出外层验证循环,结束流程 else: print('Incorrect password, try again')
关键修改说明
- 终止外层循环:确认密码匹配(
found为True)后,在文件遍历完成的代码块外添加break,直接终止外层的while True循环,完成验证流程。 - 调整错误提示逻辑:将错误提示移到文件遍历完成之后,确保仅当整个文件无匹配密码时,才打印一次错误信息。
- 优化细节:创建密码时改用
with语句管理文件,自动关闭文件;添加lower()处理用户输入的"yes/no",避免大小写导致的逻辑判断失效。
内容的提问来源于stack exchange,提问作者Luke Jaekel
相关产品推荐
相关产品推荐

