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

Python编写文本式登录注册功能时始终提示用户名或密码错误如何解决

代码问题修复方案

核心错误原因

  • 没有接收Search函数的返回值:你定义的Search函数会返回是否找到对应内容的布尔值,但你调用时没有将返回结果赋值给foundU和foundP,这两个变量始终停留在初始的False状态,所以永远触发第一个错误提示。
  • 冗余的入参:Search函数里的found参数不需要从外部传入,直接在函数内部初始化即可。
  • 逻辑隐患:后续用index()判断账号密码是否匹配的写法存在漏洞,如果有多个用户使用相同密码,index()只会返回第一个匹配项的下标,会误判正确的账号密码组合。
  • 多余的文件关闭操作:with open语法会在代码块执行完成后自动关闭文件,不需要手动调用f.close()。

修正后的完整代码

usernames = []
passwords = []
counter = 0
# 读取账号文件
with open("login_project/logins.txt", "r+") as f:
    lines = f.readlines()

for element in lines:
    if counter % 2 == 0:
        usernames.append(element.strip())
    else:
        passwords.append(element.strip())
    counter += 1

# 优化Search函数,不需要传入found参数
def Search(lista, val):
    found = False
    for i in range(0, len(lista)):
        if lista[i] == val:
            found = True
    return found

def login():
    username = input("Please enter your username: ")
    password = input("Please enter your password: ")
    # 接收函数返回的查询结果
    foundU = Search(usernames, username)
    foundP = Search(passwords, password)
    if foundU == False or foundP == False:
        print("Username or password is incorrect")
    # 优化匹配逻辑,直接判断同下标位置的账号密码是否对应
    elif passwords[usernames.index(username)] != password:
        print("Username or password is incorrect 2")
    else:
        print("Login succesful")

login()

更简洁的优化方案(可选)

你可以用字典直接存储账号和密码的对应关系,不需要维护两个列表,逻辑更清晰:

user_dict = {}
with open("login_project/logins.txt", "r+") as f:
    lines = [line.strip() for line in f.readlines()]
# 每两行一组,存为字典的键值对
for i in range(0, len(lines), 2):
    user_dict[lines[i]] = lines[i+1]

def login():
    username = input("Please enter your username: ")
    password = input("Please enter your password: ")
    if username not in user_dict:
        print("Username or password is incorrect")
    elif user_dict[username] != password:
        print("Username or password is incorrect 2")
    else:
        print("Login succesful")

login()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 05:54:03