Ask for input until exact string is input problem - python

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.

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.

Well, suppose the user inputs "y".
Your code will enter the while True loop and encounter the if condition
Is choice != "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 true
Ask for input again
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"

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

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!":

Related

Code always doing the same path regardless of input. (PYTHON) [duplicate]

This question already has answers here:
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
Closed last year.
I'm currently writing a program for a school project.
The purpose is for it to work as an online cash register.
answer = "a"
qty1 = 0
while True:
answer = str(input("\nDo you really wish to buy this? (Y/N) "))
if answer == "Y" or "y":
qty1 = int(input("\nHow much quantity of this item would you like to buy? "))
print("\nDo you really wish to buy", qty1, "pieces? (Y/N) ")
answer = str(input(""))
if answer == "Y" or "y":
print("Confirming order and returning to menu.")
break
else:
qty1=0
print("Cancelling order and returning to menu")
break
elif answer == "N" or "n":
print("Okay, returning to menu.")
break
else:
print("not valid answer")
Here is the code for the part of the program I'm having trouble with.
Whenever I reach this part of the program, the input seems to ignore whatever I put and it always goes through the if path.
Does anyone know why this is?
I'm new to programming, so sorry if this is just an easy fix.
Here's the working code which needed some formatting:
Changed these lines -> answer in ("Y", "y") and answer in ("N", "n"). This is because if answer == 'Y' or 'y' is used then 'y' will always evaluate to True which means the first if statement always executes. Also, the error in the print statement has a colon: print: - this was corrected.
answer = "a"
qty1 = 0
while True:
answer = str(input("\nDo you really wish to buy this? (Y/N) "))
print(answer)
if answer in ("Y", "y"):
qty1 = int(input("\nHow much quantity of this item would you like to buy? "))
print("\nDo you really wish to buy", qty1, "pieces? (Y/N) ")
answer = str(input(""))
print(answer)
if answer in ("Y", "y"):
print("Confirming order and returning to menu.")
break
else:
qty1=0
print("Cancelling order and returning to menu")
break
elif answer in ("N" ,"n"):
print("Okay, returning to menu.")
break
else:
print("not valid answer")

If statements running at the same time how to

if input("Raining? ") == "yes":
print("Then you should take an umbrella")
if input("Raining? ") == "no":
print("Then you should not take an umbrella ")
so I want these 2 to check yes or no at the same time so when I type no the printed answer should be "Then you should not take an umbrella" but the thing is it asks twice when I say no
example:
Raining? no
Raining? no
Then you should not take an umbrella
any ideas how I can make this work ?
I just want to ask you Raining? no and the answer to be Then you should not take an umbrella, not asking you twice and the second time works
Ask for the input before the if statement.
For example:
value = input("Raining? ")
if value == "yes":
print("Then you should take an umbrella")
elif value == "no":
print("Then you should not take an umbrella")
Just save the input to be compared later.
inp = input("Raining? ")
if inp == "yes":
print("Then you should take an umbrella")
elif inp == "no":
print("Then you should not take an umbrella ")

My python code has errors, but just in the try- except loop. [duplicate]

This question already has answers here:
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
Closed 4 years ago.
My python code has some errors in the try- except loop. If you enter an input which is not yes or no, it first prints the "yes" reply output, then once you answer the question it shows the output for if you do not enter yes or no. Here's the code:
playAgain = None
while playAgain != "Yes" or "No" or "yes" or "no" or "y" or "n":
try:
playAgain = str(input("Do you want to play again? Enter Yes or No: "))
if playAgain == "Yes" or "y" or "yes":
displayIntro()
elif playAgain == "No" or "no" or "n":
print("Oh, well. The magic 8 ball will see you next time...")
sys.exit()
except:
print("That wasn't yes or no, idiot. The magic 8 ball will not give a fortune to such an imbocile.")
Please help and thank you!
playAgain != "Yes" or "No" or "yes" or "no" or "y" or "n"
Is not a correct way to do this.
When you say playAgain != "Yes" then you need to do the same for the remaining expression. So a valid way to do what you were intended to do is the following:
playAgain != "Yes" or playAgain != "No" or playAgain != "yes" or playAgain != "no" or playAgain != "y" or playAgain != "n"
But this is ugly and too long.
Instead, use
playAgain not in ["Yes", "No", "yes", "no", "y", "n"]
In Python, we have some handy ways to deal with such problems. You can use the in operator to check if the string in question exists (or does not exist) in a list of possible values. It's also very nice to read: "if playAgain (is) not in [this list of values]".
You can even manipulate the input so it's easier for you to work with. That is, you lower all the letters and you don't check for case-sensitive input (if you really don't care about case sensitive input; do you really care if is Yes or yEs?):
playAgain.lower() not in ["yes", "y"]
Something like this should do:
while True:
playAgain = str(input("Do you want to play again? Enter Yes or No: "))
if playAgain.lower() in ["yes", "y"]:
# do something with your yes input. Consider `break` out of the endless loop.
elif playAgain.lower() in ["no", "n"]:
# do something with your no input. Consider `break` out of the endless loop.
else:
print("That wasn't yes or no.")
Note that the above loop is endless. You need to break-out according to your program logic. That is, you need to put a break statement somewhere when you need to break out of the endless loop.

python if statement evaluation with multiple values

I'm not exactly sure why but when I execute this section of code nothing happens.
while (True) :
choice = str(input("Do you want to draw a spirograph? (Y/N) "))
if choice == 'n' or 'N' :
break
elif choice == 'y' or 'Y' :
<CODE>
else :
print("Please enter a valid command.")
choice = input("Do you want to draw a spirograph? (Y/N)")
It won't work because the 'N' literal always evaluates to True within your if statement.
Your if condition currently stands as if choice == 'n' or 'N' :, which is equivalent to if (choice == 'n') or ('N'), which will always evaluate to True irrespective of the value of variable choice, since the literal 'N' always evaluates to True.
Instead, use one of the following
if choice == 'n' or choice == 'N' :
if choice in 'nN' :
if choice in ('n', 'N') :
The same holds for your elif block as well. You can read more about Truth Value testing here.
This expression doesn't do what you want:
choice == 'n' or 'N'
It is interpretted as this:
(choice == 'n') or 'N'
You might want to try this instead:
choice in 'nN'

If Statement and while loop

I'm a self taught programmer, and I just started using python. I'm having a bit of a problem, when I execute this code:
x = 0
while x == 0:
question = raw_input("Would you like a hint? ")
if question == "y" or "yes":
print "Ok"
first.give_hint("Look over there")
x = 1
elif question == "n" or "no":
print "Ok"
x = 1
else:
print "I'm Sorry, I don't understand that"
just so you know, first.give_hint("Look over there") was defined in a class earlier in the program, I just left that part out for sake of space. When I run the program no matter what I type, I get the first case "Look over There", I've been trying to figure out what the problem is, but I just don't understand. If you guys could help me, I'd appreciate it a lot.
The problem is this line:
if question == "y" or "yes":
"yes" will always evaluate to True.
What you really want is:
if question == "y" or question == "yes":
Similar changes must be made for the other conditions.
You made a mistake in your if statement, this should be :
if (question == "y") or (question == "yes"):
print "Ok"
Explanation :
(question == "y" or "yes")
is equivalent to :
(question == "y" or "yes" != 0) # operator 'or' having the prevalence
"yes" string being non-null, ("yes" != 0) always return True, and so do your whole original condition.
The condition is wrong. You have question == "y" and a logical or with the string "yes" that is always True. That is why it evaluates to the first case every time.
Try to change to if question[0] == 'y'

Categories