如何使用input()并将元素与数据库匹配

database = {'User Name':['John frecks','Nadal alpha','Rick Ziani'],
         'Code':['9264','8345','2675']}



for i in database:
    name = input('Enter your name: ')
    if name in database['User Name']:
        print('Welcome', name,'Enter your code')
    else:
        print('You are not a client! Enter your name again!')
        name = input('Enter your name: ')
        break
    code = input('Enter your code: ')
    if code in database['Code']:
        print('you are welcome')
        break
    else:
        print('your code is wrong!')
        break

我想要的结果,如果一切正确:

Enter your name: Nadal alpha
Enter your code: 8345
Your are welcome

我程序中的问题是无论代码或名称是什么,我仍然会得到相同的结果。 例如:

Enter your name: Nadal alpha
Enter your code: 2675 #this is Rick Ziani's code
You are welcome

也许,我没有正确地编写程序,如果有优化的方法,请告诉我。 谢谢

评论
  • biu~
    biu~ 回复

    您遇到的问题是数据库无法以一种有用的方式在事物之间进行映射。您的键只是常量字符串,值是列表。也许您可以在列表中使用索引来找出哪些代码与哪个名称相对应,但是还有更好的方法。

    使您的数据库字典直接从名称映射到代码,没有列表:

    database = {'John frecks': '9264', 'Nadal alpha': '8345', 'Rick Ziani': '2675'}
    

    Now you can check if a name is know with if name in database. And you can lookup the corresponding code with database[name].

  • 萌小丁
    萌小丁 回复

    设计字典的方式并不是创建字典的最佳实践。但是出于问题的考虑,让我们保持现状。

    问题是,除了代码和用户名的顺序外,您没有建立任何关系,这对python本身没有任何意义

    这是在您的代码中修复它的方法,为方便起见,我将添加注释:

    for i in database:
        user_index = 0 # you have to start a variable to be used in inner scopes
        name = input('Enter your name: ')
        if name in database['User Name']:
            user_index = database['User Name'].index(name) # get the index of the entered name
            print('Welcome', name,'Enter your code')
            print(database['Code'][user_index])
        else:
            print('You are not a client! Enter your name again!')
            name = input('Enter your name: ')
            break
        code = input('Enter your code: ')
        if code in database['Code'] and code == database['Code'][user_index]:
            # in the second part of the line above, you make sure that code and name have the same index
            print('you are welcome')
            break
        else:
            print('your code is wrong!')
            break