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

如何验证用户名与对应索引的密码匹配?Python登录系统求助

解决方案:精准匹配用户名与对应密码

嘿,你的思路非常正确——先定位用户名的索引再匹配对应密码,这确实是解决用户名密码错位问题的核心。不过你的现有代码还有几个可以优化的地方,比如递归调用Login()可能导致的栈溢出(如果用户多次输入错误,递归会不断压栈最终报错),还有循环逻辑的冗余。我给你整理了两种靠谱的实现方式:

方式一:基于列表索引的匹配(贴合你的原始思路)

这种方式严格按照你想要的“找索引→匹配对应密码”的逻辑来实现:

def login():
    # 注意:实际项目里绝对不要硬编码密码,这里只是示例
    usernames = ["alice", "bob", "charlie"]
    passwords = ["alice123", "bob456", "charlie789"]
    
    user_input = input("Please enter your username: ")
    pw_input = input("Please enter your password: ")
    
    try:
        # 找到输入用户名在列表中的索引
        user_index = usernames.index(user_input)
        # 验证对应索引的密码是否匹配
        if passwords[user_index] == pw_input:
            print("Login Successful")
        else:
            print("Password does not match")
            # 重新调用函数代替递归,避免栈溢出问题
            login()
    except ValueError:
        # 当用户名不在列表中时,index()会抛出ValueError
        print("User not recognised")
        login()

# 启动登录流程
login()

方式二:用字典存储凭据(更推荐的简洁方案)

其实用字典来存储用户名和密码的键值对是更符合逻辑的选择,它天然就保证了用户名和密码的一一对应关系,代码也更简洁易维护:

def login():
    user_credentials = {
        "alice": "alice123",
        "bob": "bob456",
        "charlie": "charlie789"
    }
    
    user_input = input("Please enter your username: ")
    pw_input = input("Please enter your password: ")
    
    if user_input in user_credentials:
        if user_credentials[user_input] == pw_input:
            print("Login Successful")
        else:
            print("Password does not match")
            login()
    else:
        print("User not recognised")
        login()

login()

几个关键的改进点:

  • 避免了深层递归的栈溢出风险:用重新调用函数的方式替代递归(如果想更优雅,还可以用while循环实现重复输入逻辑)
  • 逻辑更清晰:要么找到用户名验证密码,要么直接提示用户不存在,去掉了冗余的循环判断
  • 字典方式维护更方便:新增用户时只需要添加一组键值对,不用同步修改两个列表

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 06:44:20