【问题标题】:Using a for loop to find a username and password in a dictionary使用 for 循环在字典中查找用户名和密码
【发布时间】:2023-01-29 12:25:40
【问题描述】:

我试图让用户输入用户名和密码,如果输入错误,程序必须反复要求用户输入用户名和密码,直到输入正确的用户名和密码

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

while True:
    user_input = input('Enter your username: ')

    for username, data in users.items():

        if user_input == username:
            password = input('Enter the password: ')
    
            if password == data['password']:
                print('Welcome')
                break

            else:
                print('The password you have entered is incorrect')
                continue      
        else:
            print('The username does not exist')
            continue

    break

第一个 if 语句没有选择用户“man”和“cool”。它只是拿起“管理员”

如果我输入“admin”然后输入不正确的密码,“显示用户名不正确”,应该显示“密码不正确”

我该如何解决?

【问题讨论】:

  • 你有问题吗?

标签: python dictionary for-loop while-loop


【解决方案1】:

对于这种问题,使用“in”语句确实很有用。它检查字典中是否存在某些内容,而不是您必须直接检查每个项目。我认为这段代码可以满足您的需求。

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

while True:
    user_input = input('Enter your username: ')

    if user_input in users:
        password = input('Enter the password: ')

        if password == users[user_input]['password']:
            print('Welcome')
        else:
            print('The password you have entered is incorrect')
            continue
    else:
        print('The username does not exist')
        continue
    break

至于为什么你的代码不起作用,我相信你的问题是当你检查名字是否不是那个名字时(即使是另一个正确的名字)你的 else 语句打印它不存在并继续。

【讨论】:

  • @theramannoodle 如果这回答了你的问题,请接受它。如果不是,请对其进行评论以说明该解决方案为何不起作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-18
  • 1970-01-01
  • 1970-01-01
  • 2020-11-27
  • 2014-06-21
相关资源
最近更新 更多