-1

I have written a program that serves the starting basis for a login menu. It should only allow two inputs; "1" or "2". If they enter 1, they continue as an existing user, but if they enter 2 they continue as a new user. I have a while loop to prevent the user from inputting anything besides these two values.

Why does the code only allow the user to input a "1" to continue the code, but not the "2". I've looked online, but I haven't seen the way people would code or in a while loop. Could anyone make the necessary adjustments to the or so that it works? Thanks.

Edit: Best response by "bastelflp".

#Program menu
YESorNo = input("""
[---------------------------------]

      Welcome to the program!

[---------------------------------]

     Are you an existing user?

 1. [YES]
 2. [NO]

-----------------------------------
Type [1] for "YES" or [2] for "NO".

""")

while YESorNo.strip() != ("1" or "2"):
    YESorNo = input("""
[---------------------------------]

     Welcome to the program!

[---------------------------------]

     Are you an existing user?

 1. [YES]
 2. [NO]

-----------------------------------
Type [1] for "YES" or [2] for "NO".

""")

if YESorNo == "1":
        print("Welcome back!")

elif YESorNo == "2":
        print("Welcome!")
Spencer
  • 29
  • 1
  • 6
  • Please don't "fix" your questions. The question and answers could make no sense for future readers. If your solution is different to the other answers, post it as an answer. If your problem was trivial, delete the question. Otherwise, accepting an answer indicates that your problem was solved, and nothing further needs to be done. – robinCTS Nov 17 '17 at 00:36

2 Answers2

4
YESorNo.strip() != ("1" or "2")

Since or is an operator, "1" or "2" is evaluated before the comparison. The string "1" is truthy, so the result of "1" or "2" is "1". So the original expression simplifies to YESorNO.strip() != "1". For more details, I suggest you read about truthiness in Python. Also you should learn more about the order of evaluation of operators.

To fix the problem you can do this instead:

YESorNo.strip() != "1" and YESorNo.strip() != "2"

or this:

not (YESorNo.strip() == "1" or YESorNo.strip() == "2")

or this:

YESorNo.strip() not in ["1", "2"]

The first two take advantage of the correct order of operation evaluation to do what you want. The last alternative uses a list of options to compare against, which is closer to your original code.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
3
YESorNo.strip() != ("1" or "2")

This will get evaluated in the following order;

Brackets first

YESorNo.strip() != "1"

Then equality.

You need to do either this;

YESorNo.strip() not in ("1", "2")

or

not (YESorNo.strip() != "1" and YESorNo.strip() != "2")
Shadow
  • 8,749
  • 4
  • 47
  • 57