MentalCombination
MentalCombination

Reputation: 63

Ask for input until exact string is input problem

This is my Python code:

choice = (input("Are you signed up? (y/n) "))

print(choice)

while True:
    if choice != "y" or choice != "n":
        choice = (input("Are you signed up? (y/n) "))
        print(choice)
    else:
        break

I want the program to keep asking the user for input until they input "y" or "n". The problem is it never accepts the input, even if they do input "y" or "n".

When I print what they inputted (that's a real word) it says that it's "y" or "n" but it still won't accept it.

I've been using Python for some time now and I'm just trying something out today but I can't figure this out for some reason, I feel like it's something simple and obvious but I'm stupid to notice it.

Can someone explain this to me, please? Thank you.

Upvotes: 1

Views: 90

Answers (4)

Keir
Keir

Reputation: 53

You need and instead of or in this case.

    if choice != "y" and choice != "n":

or if you prefer you can do

    if not (choice == "y" or choice == "n"):

You can also do:

    if choice not in ("y", "n"):    # THIS ONE IS PROBABLY THE BEST

or because these are each 1-character you can do:

    if choice not in "yn":

You can also do:

    if choice not in "Randy!" or choice in "Rad!":

Upvotes: 1

DineshKumar
DineshKumar

Reputation: 1739

As everyone has already pointed out the problem in your code, I am just adding a cleaned version of your code.

while True:
    choice = (input("Are you signed up? (y/n) "))

    if choice == "y" or choice == "n":
        print(f"Your choice is {choice}")
        break

Upvotes: 1

ForceBru
ForceBru

Reputation: 44838

Well, suppose the user inputs "y".

  1. Your code will enter the while True loop and encounter the if condition
  2. Is choice != "y" or choice != "n", where choice == 'y', true or false?
    1. "y" != "y" is false, check the next condition
    2. "y" != "n" is true, so the whole condition is true
  3. Ask for input again
  4. Goto (1)

Same thing happens for choice == "n".


However, you want a condition that says not (choice == "y" or choice == "n"). According to De Morgan's laws:

not (a or b) == (not a) and (not b)

So your code translates into:

(not (choice == "y")) and (not (choice == "n"))
=> choice != "y" and choice != "n"

Upvotes: 1

mkrieger1
mkrieger1

Reputation: 23144

Since choice cannot be 'y' and 'n' at the same time, one of choice != 'y' and choice != 'n' is always true.

You need to use and, not or.

Upvotes: 1

Related Questions