我正在尝试使用字典构建一个简单的登录和密码应用程序。除了检查登录名是否与密码匹配(在底部显示“登录成功!”)之外,它工作得很好。
如果我要创建登录名“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: ")
if login in users and passw in users: # login matches password
print "Login successful!\n"
else:
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()