cking cking - 1 month ago 4
Python Question

What's going on with my if-else statement? (Python 3.3)

I'm writing conditional statements for a billing program project. It's a bit advanced for a beginner I know but I welcome the challenge. Anyways, I plan on starting the program with asking for username and password. So this is my first coding for the program.

print ("Hello and welcome to Billing Pro, please enter your username and password to access the database.")

username = input ("Enter username:")

if username == "cking" or "doneal" or "mcook":
print ("Valid username.")
else:
print ("Invalid username. Please try again.")


password = input ("Enter password:")

if password == "rammstein1" or "theory1" or "tupac1":
print ("Valid password. User has been verified.")
else:
print ("Invalid password. Access denied.")


Now at first when I ran this code if I had typed in anything other than the three choices for username Python printed out the 'invalid username' line. For some reason now, it's printing out 'valid username' and then going ahead with the password prompt. Also if I input anything other than the choices for passwords it will always read out the 'valid password' prompt.

Also how do I loop the username prompt when the user inputs something other than the three choices? Should I be using a while statement instead of if-else or can a while statement be placed at the end of the if-else statement to trigger the prompting again?

Oh and I know you can't tell because my crappy formatting in the question, but I did use proper indentation on the script itself.

Answer

The problem with your boolean expressions themselves is that they're always True.

if a == 'b' or 'c' is like if (True|False) or 'c', and since 'c' is truthy, it's True regardless of the first expression (a == 'b').

You either want a == 'b' and a == 'c'… or the more succinct a in {'b', 'c'…}, which checks if a is a member of the set.

If you want to loop, use a loop :)

while username not in {"cking", "doneal", "mcook"}:
    print ("Invalid username. Please try again.")
    username = input ("Enter username:")
print ("Valid username.")
Comments