You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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')

关键修改说明

  1. 终止外层循环:确认密码匹配(found为True)后,在文件遍历完成的代码块外添加break,直接终止外层的while True循环,完成验证流程。
  2. 调整错误提示逻辑:将错误提示移到文件遍历完成之后,确保仅当整个文件无匹配密码时,才打印一次错误信息。
  3. 优化细节:创建密码时改用with语句管理文件,自动关闭文件;添加lower()处理用户输入的"yes/no",避免大小写导致的逻辑判断失效。

内容的提问来源于stack exchange,提问作者Luke Jaekel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 03:01:11