pythonpython-3.xif-statementnested-if

How to use if-else to check the value of two variables (username, password), and if one is wrong, print out which variable is wrong?


In the task it is written that the code should look something like this:

if [selection]:
    [code]
    
    if [selection]:
        [code]
    else:
        [code}
else:
    [code]

Output should be:

Give name: Peter
The given name is wrong.

or

Give name: John
Give password: Monkeys?
The password is incorrect.

or

Give name: John
Give password: ABC123
Both inputs are correct!

So far the best I've come up with is:

name = input("Give name:")
password = input("Give password:")
if name == "John":
    if password == "ABC123":
        print("Both inputs are correct!")
    else:
        print("The given password is incorrect.")
else:
    print("The given name is wrong.")

But so far, when I type in the correct data, it all works fine. But if I put in the wrong name it doesn't tell me that the name is wrong but asks for password right away and after that tells me the name is wrong.

It should tell me immediately that the name is wrong, and if the name is right, then move on to asking for a password.


Solution

  • The outer if should check for name, then the inner if should check the password.

    name = input("Give name:")
    if name == "John":
        password = input("Give password:")
        if password == "ABC123":
            print("Both inputs are correct!")
        else:
            print("The given password is incorrect.")
    else:
        print("The given name is wrong.")