python检查用户对字典的详细信息

时间:2017-04-23 19:11:06

标签: python-3.x

usr_pwd = {'adam' : 'Test123', 'alice' : 'Test321'}
u_name = input("Please specify your username: ")
u_pwd = input("Please specify your password: ")
usr_pwd[u_name] = u_pwd
if usr_pwd.get(u_name) == u_pwd:
    print('ok')

我感到沮丧,需要一些帮助。如何检查字典是否和给定的用户名和密码组合有效?我找到了get模块,但问题是:

  

如果key在字典中,则返回key的值,否则返回default。如果未给出default,则默认为None,因此此方法永远不会引发KeyError。

我也找到了这个Simple username and password application in Python但代码:

 if login in users and passw in users: # login matches password
      print "Login successful!\n"

对我不起作用......

1 个答案:

答案 0 :(得分:1)

有几种流行的方法可以检查dict中的信息,每种方法都有自己的位置。以下是一些选项

usr_pwd = {'adam' : 'Test123', 'alice' : 'Test321'}
u_name = input("Please specify your username: ")
u_pwd = input("Please specify your password: ")

# use get
if usr_pwd.get(u_name) == u_pwd:
    print('ok')
else:
    print('user name or password incorrect')

# check first
if u_name in usr_pwd:
    if usr_pwd[u_name] == u_pwd:
        print('ok')
    else:
        print('bad password')
else:
    print('bad user name')

# try and die
try:
    if usr_pwd[u_name] == u_pwd:
        print('ok')
    else:
        print('bad password')
except:
    print('bad user name')