def login():
usern = ""
pwd = ""
logged = False
while str(usern) not in keys and str(pwd) not in value:
while str(usern) not in keys:
usern = input("please enter Username: ")
if usern not in keys:
print("Incorrect username!")
pwd = input("Please enter your password!: ")
if str(pwd) in value:
break
else:
print("incorrect password!")
print("welcome")
login()
this code was supposed to check username and password values where I stored them in another file (key and value). and print out welcome if they were correct.
I was expecting right after entering the password if it is incorrect, it was to start again by asking usename again but the main while loop doesnt seem to recognize the second condition the loop breaks whether i enter a correct password or not. (I havent shown the usernames and password as they are on another file and i imported them as lists.)
CodePudding user response:
Is your indentation correct? That pwd
line looks a bit off, it could change everything. Also, the if-else
statements should be directly below pwd
. Something like this:
def login():
usern = ""
pwd = ""
logged = False
while str(usern) not in keys and str(pwd) not in value:
while str(usern) not in keys:
usern = input("please enter Username: ")
if usern not in keys:
print("Incorrect username!")
pwd = input("Please enter your password!: ")
if str(pwd) in value:
break
else:
print("incorrect password!")
print("welcome")
login()
CodePudding user response:
Your problem is with the line:
while str(usern) not in keys and str(pwd) not in value:
The loop will only continue when BOTH usern
and pwd
are not valid inputs. So after you enter a valid username, and then enter an invalid password, your code prints "incorrect password", but then the while
loop exits because usern
is now a correct value. If you instead do this:
while str(usern) not in keys or str(pwd) not in value:
you should get the behavior you expect (assuming you fix the indentation problem mentioned in the other answer).
Your code is correct if both keys
and value
are lists. Since value
is singular, I'm wondering if that might be a single string rather than a list of strings. If so, then using in
to test passw
against value
isn't what you want. You instead want to use ==
in that case.
A minor hint...you don't need any of your str()
casts. The values you are operating on are always already strings.