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

Python登录验证逻辑异常:错误密码触发无效用户名提示

问题描述

作业要求实现登录功能:

  • 提示用户输入用户名和密码,有效账号密码存储在user.txt文件中
  • 若用户名不存在,或用户名正确但密码错误,需显示对应错误提示
  • 需重复要求用户输入直至提供有效凭据

实际遇到的问题:尝试用while循环和if判断实现,但输入错误密码时,程序总是输出“未输入有效用户名”的错误提示。

用户原代码:

usernames = [] # list for usernames
passwords = [] # list for passwords

with open("user.txt", "r") as file: # open user file in a read capacity as we are not writing to it

    for lines in file:
        temp = lines.strip() # Strip function is done first in order to remove newline character
        temp = temp.split(", ") # Split the username and password by the seperator of a comma and a space

        usernames.append(temp[0]) # By appending the index 0 we can add to usernames liste
        passwords.append(temp[1]) # By appending the index 1 we can add to passwords list

user_name = input("Please enter your username : ")
pass_word = input("Please enter your password : ")

if user_name not in usernames and pass_word not in passwords:
    print("You have not entered a valid username and password, please try again")
    user_name = input("Please enter your username : ")
    pass_word = input("Please enter your password : ")

elif user_name in usernames and pass_word not in passwords:
     print("You have not entered a valid password, please try again")
     user_name = input("Please enter your username : ")
     pass_word = input("Please enter your password : ")

elif user_name not in usernames and pass_word in passwords:
    print("You have not entered a valid username, please try again")
    user_name = input("Please enter your username : ")
    pass_word = input("Please enter your password : ")
问题分析与修复

错误原因

  1. 用户名与密码未关联:将用户名和密码分别存入两个列表,无法确认密码是否属于当前输入的用户名。例如输入正确用户名+其他用户的密码时,程序会误判密码有效,导致逻辑混乱。
  2. 无循环输入逻辑:仅处理一次错误就结束程序,未实现“重复输入直至有效”的要求。
  3. 条件判断有漏洞:存在既不满足if也不满足任何elif的情况,导致程序无提示直接终止。

修复后的代码

# 用字典存储用户名与对应密码,实现一一关联
user_credentials = {}

with open("user.txt", "r") as file:
    for line in file:
        # 去除换行符并分割用户名和密码
        line = line.strip()
        username, password = line.split(", ")
        user_credentials[username] = password

# 循环请求输入,直到验证通过
while True:
    user_name = input("请输入用户名:")
    pass_word = input("请输入密码:")
    
    # 先验证用户名是否存在
    if user_name not in user_credentials:
        print("用户名无效,请重新输入。")
    else:
        # 用户名存在时验证密码是否匹配
        if user_credentials[user_name] == pass_word:
            print("登录成功!")
            break  # 验证通过,退出循环
        else:
            print("密码错误,请重新输入。")

修复说明

  • 使用字典替代独立列表,确保每个用户名和对应的密码绑定,从根源解决了关联问题。
  • while True实现无限循环,验证通过后用break退出,满足重复输入的需求。
  • 分层判断逻辑:先检查用户名,再验证对应密码,错误提示精准,不会出现混淆。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 21:12:07