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

如何在Python中实现用户名与对应密码的精准匹配登录验证

问题分析与解决方案

核心问题:登录验证逻辑错误

你的登录函数user_login中,密码验证的条件逻辑完全错误:

if username in users_data['User name'].tolist() == password in users_data['Password'].tolist():

这行代码实际是判断「用户名存在」和「密码存在」两个布尔值是否相等——只要输入的密码是数据库里任意用户的密码,这个条件就会成立,自然导致任意有效密码都能登录成功。

正确逻辑应该是:找到当前输入用户名对应的行,取出该行密码与输入密码比对。

修正后的登录函数

def user_login(users_data):
    counter = 0
    while True:
        # 读取最新用户数据,避免缓存过期
        users_data = pd.read_csv("users.csv")
        username = input("Please enter your username> ")

        while not check_user_login(username):
            username = input("Invalid username, please try again> ")

        password = input("Please enter your password> ")
        # 定位对应用户名的行
        user_row = users_data[users_data['User name'] == username]
        # 取出该行的密码(用户名唯一,直接取第一个结果)
        correct_password = user_row['Password'].iloc[0]
        
        if password == correct_password:
            print("Welcome")
            break  # 验证成功后退出登录循环
        else:
            print("Details are wrong! Please try again")
            counter += 1
            if counter == 3:
                print(f"You tried wrongly {counter} times. Goodbye.")
                exit()

其他优化点

  1. 修复注册逻辑重复问题
    主函数中,新用户分支会重复调用get_user_input_data(),导致用户重复输入注册信息,修正后:
if __name__ == '__main__':
    robot = string.digits + string.ascii_letters
    initial_code = "".join(random.choice(robot) for i in range(6))
    print(f"Welcome to the Verification page,\nthe initial verification code is: {initial_code}\n")

    counter = 0
    while True:
        user_input_initial_code = input("Repeat the initial verification code>> ")
        if user_input_initial_code == initial_code:
            print("\nWelcome!\n")

            returning_user = input("Got an account? (yes/no)> ")
            while returning_user not in ["yes", "no"]:
                returning_user = input("Invalid answer, options are: (yes/no)")

            if returning_user == 'yes':
                user_login(users_data)
            else:
                # 直接处理新用户注册,避免重复调用
                file_exists = exists("users.csv")
                if file_exists:
                    users_data = pd.read_csv("users.csv")
                else:
                    users_data = pd.DataFrame({NAME: [], 'User name': [], 'Password': [], 'Strikes': []})

                input_name, input_username, input_password = get_user_input_data()
                users_data = pd.concat([users_data, pd.DataFrame({NAME: input_name, 'User name': input_username,
                                                                  'Password': input_password, 'Strikes': [0]})])
                users_data.to_csv('users.csv', index=False)
                print("Registration successful!")
            break
        else:
            print("Wrong input code!")
            counter += 1

        if counter == 3:
            print(f"You tried wrongly {counter} times. Goodbye.")
            exit()
  1. 清理冗余代码
  • 删除user_login中无意义的open('users.csv', "r")语句
  • 合并重复的用户名检查函数:
    def is_username_exist(username):
        return username in users_data['User name'].tolist()
    
    注册时用while is_username_exist(username),登录时用while not is_username_exist(username)即可。
  1. 修复密码生成器变量作用域问题
    get_user_input_data中使用的robot变量定义在主函数,会导致函数无法访问,将其移到函数内部:
def get_user_input_data():
    robot = string.digits + string.ascii_letters
    # ... 原有代码

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 21:37:02