我正在尝试使用字典构建一个简单的登录和密码应用程序。它工作正常,除了检查登录名是否与密码匹配的部分(在底部显示“登录成功!”)。
如果我要创建登录名'a'和密码'b',然后创建登录名'b'和密码'a',如果我尝试使用登录名'a'和密码'a'登录,它会登录我。它只是检查这些字符是否存在于字典中的某个地方,而不是它们是否是一对。
任何建议如何解决这个问题?
users = {}
status = ""
while status != "q":
status = raw_input("Are you a registered user? y/n? Press q to quit: ")
if status == "n": #create new login
createLogin = raw_input("Create login name: ")
if createLogin in users: # check if login name exist in the dictionary
print "Login name already exist!\n"
else:
createPassw = raw_input("Create password: ")
users[createLogin] = createPassw # add login and password
print("\nUser created!\n")
elif status == "y": #login the user
login = raw_input("Enter login name: ")
if login in users:
passw = raw_input("Enter password: ")
print
if login in users and passw in users: # login matches password
print "Login successful!\n"
else:
print
print("User doesn't exist!\n")
编辑
现在这正在工作,为了便于阅读,我正在尝试将应用程序划分为三个功能。它有效,除了我得到无限循环。
任何建议为什么?
users = {}
status = ""
def displayMenu():
status = raw_input("Are you a registered user? y/n? Press q to quit: ")
if status == "y":
oldUser()
elif status == "n":
newUser()
def newUser():
createLogin = raw_input("Create login name: ")
if createLogin in users: # check if login name exists
print "\nLogin name already exist!\n"
else:
createPassw = raw_input("Create password: ")
users[createLogin] = createPassw # add login and password
print("\nUser created!\n")
def oldUser():
login = raw_input("Enter login name: ")
passw = raw_input("Enter password: ")
# check if user exists and login matches password
if login in users and users[login] == passw:
print "\nLogin successful!\n"
else:
print "\nUser doesn't exist or wrong password!\n"
while status != "q":
displayMenu()