Skip to content
Advertisement

im having trouble with this code, although it works but not the way i want

users = {
    "Armin": "1234",
    "Mehrnaz": "4321"
}

entered_username = input("Enter your username: ")
entered_password = input("Enter your password: ")

while entered_username in users and users[entered_username] != entered_password:
    print("Wrong, Try again")
    entered_username = input("username: ")
    entered_password = input("password: ")
else:
    print("You have logged in successfully ")

In this code if i put the right username and wrong password, I get the “Wrong, Try again”, but if I put the wrong username and wrong password, i still get the “You have logged in successfully”

help please, thank you <3

Advertisement

Answer

There’re two conditions in your loop:

  1. entered_username in users ;
  2. users[entered_username] != entered_password .

If any of those conditions fail, your loop won’t be started and else section will be executed.

When you enter username which doesn’t exist in users dictionary first condition will be false.

You may use dict.get() which will return None by default if key doesn’t exist in dictionary and simplify your loop condition to:

while users.get(entered_username) != entered_password:
    ...
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement