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

Python字典用户认证代码问题:无法识别非admin用户及错误提示异常

修复用户登录验证代码的问题

原代码的核心问题在于错误地使用for循环遍历用户字典,导致每次输入用户名时,都会和字典里的每个用户逐一比对,不匹配就立刻输出错误信息,完全不符合登录验证的逻辑。下面是修复后的代码:

users = {
    'admin': {'password': 'adm1n'},
    'man': {'password': 'thing'},
    'cool': {'password': 'guy'}
}

while True:
    user_input = input('Enter your username: ')
    # 先检查用户名是否存在于用户字典中
    if user_input not in users:
        print('The username does not exist')
        continue  # 用户名不存在,重新输入
    
    # 用户名存在,验证密码
    password = input('Enter the password: ')
    if password == users[user_input]['password']:
        print('Welcome')
        break  # 验证成功,退出循环
    else:
        print('The password you have entered is incorrect')
        # 密码错误,回到循环开头重新输入

修复说明:

  • 去掉了多余的for循环,直接用user_input in users判断用户名是否存在,避免了遍历过程中频繁输出错误信息的问题
  • 调整了逻辑顺序:先验证用户名,存在再验证密码,逻辑更清晰
  • 只有当用户名完全不存在时才输出「用户名不存在」,密码错误时只会提示密码问题,解决了原代码的两个bug
  • 保留了外层的while True循环,确保验证失败时可以重复输入直到正确

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 03:01:21