辞書を使用して、単純なログインとパスワードのアプリケーションを構築しようとしています。ログインがパスワードと一致するかどうかをチェックする部分を除いて、正常に動作します (「ログイン成功!」と表示されている下部)。
ログイン「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")
編集
これが機能するようになったので、読みやすくするために、アプリケーションを 3 つの関数に分割しようとしています。無限ループになることを除いて、動作します。
なぜ何か提案はありますか?
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()