Reputation: 63
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
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
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
Reputation: 44838
Well, suppose the user inputs "y"
.
while True
loop and encounter the if
conditionchoice != "y" or choice != "n"
, where choice == 'y'
, true or false?
"y" != "y"
is false, check the next condition"y" != "n"
is true, so the whole condition is trueSame 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
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