Home > OS >  Python username, password if-else nesting problem
Python username, password if-else nesting problem

Time:02-05

I am learning python and have a task to solve. 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 correct data it all works fine but if I put in 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, if right then moves on to asking for a password. So far tutorials have not really helped me.

CodePudding user response:

You should spend a little more time about how python code runs, btw

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.")

  •  Tags:  
  • Related