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 3 years ago.
Currently working on my first program and my Else statement isn't working in the following code:
info = input("<Y/N>")
if (info == "Y" or "y"):
print("Calculating...")
else:
raise SystemExit
The program just continues to
print("Calculating...")
even if the input isn't "Y" or "y"
if (info == "Y" or "y"):
is equivalent to saying
if ((info == "Y") or ("y"))
Since y is not zero, null, or equivalent, it evaluates to true.
The either of the following will do:
if (info == "Y" or info == "y")
if (info in ("y", "Y"))
if (info.lower() == "y")
You should write something like this:
info = input("<Y/N>")
if (info == "Y" or info == "y"):
print ("Calculating...")
else:
raise SystemExit
In your statement:
info == "Y" or info == "y"
"y" is always True
What's happening is that the or operator is treating the left and right side as boolean (True and False) statements. What it's looking to see on the left side is info == "Y" which might be true or false depending on the input. On the right side it's seeing "y" and checking if "y" is true. In python non-empty strings count as true when evaluated as booleans. To fix this here are two ways to check.
if info == "Y" or info == "y":
if info in ["y", "Y"]:
Let me just add this to the above answers: a more pythonic way of checking
if (info == 'Y' or info == 'y')
is done by
if info.lower() == 'y'.
Of course, info needs to be a string.
Related
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)
How to test multiple variables for equality against a single value?
(31 answers)
Closed 17 days ago.
I have written this very simple code. I am new to programming. But I seem to dont understand why this loops doesnt break when I give it "N" for an answer when I run it.
while (True):
name = input("What is your name?\n")
print(f"Hello {name}, how are you today?")
answer = input("would you like to continue with the conversation? Reply with 'Y' or 'N'\n")
if answer == "y" or "Y":
continue
elif answer == "N" or "n":
break
else:
print("Kindly only answer with 'Y' or 'N'")
I wanted this to get out of loop and break the program when I enter "N"
You need to include answer == in both sides of the conditionals.
i.e.
while (True):
name = input("What is your name?\n")
print(f"Hello {name}, how are you today?")
answer = input("would you like to continue with the conversation? Reply with 'Y' or 'N'\n")
if answer == "y" or answer == "Y":
continue
elif answer == "N" or answer == "n":
break
else:
print("Kindly only answer with 'Y' or 'N'")
This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 1 year ago.
Background:
I'm experimenting with while loops and I just made a simple program nested in a while loop.
Code:
while True:
userinput = input("Is nem jeff? ")
if userinput == "y" or "yes" or "Y" or "Yes":
print ("YAY!")
elif userinput == "n" or "no" or "N" or "No":
print ("das sad :(")
else:
print ("wrong input")
break
Problem:
My program should be looping until the user types in an invalid input, but instead, it always returns the value nested in the if statement, no matter what I type in. What am I doing wrong?
Your conditionals aren't doing what you think they are.
In Python, a non-zero-length string evaluates to True in a boolean
context. The or operator performs a boolean or operation between
the lefthand operand and the righthand operand.
So when you write this:
if userinput == "y" or "yes" or "Y" or "Yes":
What you are saying is this:
if (userinput == "y") or True or True or True:
Which will always evaluate to True. You want to write instead:
if userinput == "y" or userinput == "yes" or userinput == "Y" or userinput == "Yes":
Or more simply:
if userinput.lower() in ['y', 'yes']:
The reason false down to truthsy or falsy in if conditions.
based on your initial code block
print('y'=='yes'or'y')
[output] y
print('n'=='yes'or'y')
[output] y
based on the above you can see that regardless of you input, your first if statement would be evaluated as True.
rather than doing that, try doing this instead.
while True:
userinput = input("Is nem jeff? ").lower()
if userinput in ['yes','y']:
print ("YAY!")
elif userinput in ['no','n']:
print ("das sad :(")
else:
print ("wrong input")
break
This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 2 years ago.
questionnumber=0
color=("Red")
userask=input("What color of the rainbow am I thinking of? ")
color = userask
if color == "Red":
print("CORRECT")
else:
print("INCORRECT")
questionnumber = questionnumber+1
#print(questionnumber)
while color != "Red":
userask=input("What color of the rainbow am I thinking of? ")
color = userask
if color == "Red":
print("CORRECT")
else:
print("INCORRECT")
questionnumber = questionnumber+1
#print (questionnumber)
if questionnumber>3:
quitter=input("Do you want to quit? ")
if quitter == "yes"or"Yes":
break
else:
continue
So the idea is you have to guess the correct color which in this case is red. But after three attempts, the program asks the user if they want to quit; if yes, the while loop stops, and if no, the while loop continues for another three attempts. I can't seem to figure out why the loop ends regardless of the user's answer.
Your problem is that:
if quitter == "yes"or"Yes"
is based on a misunderstanding of Python logic statements.
It is not interpreted as if quitter == ("yes"or"Yes") as you intended, but it is actually interpreted as:
if (quitter == "yes") or ("Yes")
Any non-blank string evaluates to True, so the break is always executed.
A better way of writing this would be:
if quitter.lower() == "yes":
This converts the contents of quitter to lower case and checks that, so you don't need to check upper and lower case, and other variants like "YES".
Please change this statement to as below :
if ((quitter == "yes") or (quitter == "Yes")):
After prompting the user if they want to quit, change the if statement to
if quitter == "yes" or quitter == "Yes":
break
else:
continue
The reason the program exits is because it's evaluating the string 'Yes' on it's own as True which means the or statement evaluates as True and thus break is ran. You have to specify quitter both before and after the or statement.
truth_val = bool('Yes')
print(truth_val)
>>>True
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 6 years ago.
So the problem I'm having is with this part of a simple script for a Chat Bot about Programming. But when I test this part of the script and type in 'B' as my input, it says ('Panda: I'm glad you share my enthusiasm.') which is what is mean't to happen if I input A! Can someone please point out to me what I'm doing wrong?
invalidAnswer2 = true
while invalidAnswer2 == true :
answer2 = input (user)
if answer2 == ('a') or ('A') :
print ('Panda: I'm glad you share my enthusiasm.')
invalidAnswer2 = false
elif answer1 == ('b') or ('B') :
print ('Panda: I wish. I am actually British, but I dream of going to America!')
print ('Panda: *Cough* Um anyway that was rather unproffesional of me.')
invalidAnswer2 = false
else :
invalidAnswer()
invalidAnswer2 = true
Thank You for helping me fix it. It was a simple typo after all that XD
The problem is your that your first if statement is always True:
if answer1 == "a" or "A"
Will always yield true, because it's really asking:
if (answer1 == "a") or ("A")
And "A" will always return True.
What you meant is probably:
if answer1 == "a" or answer1 == "A"
or the better option:
if answer1.lower() == "a"
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 6 months ago.
When I run this in my program, the question goes through, however no matter the answer, the "No" option always runs. If I switch the option order, the "Y" option will only run and it will always go straight to start. I'm sure I'm missing something simple, I just don't know what.
infoconf = raw_input("Is this information correct? Y/N: ")
if infoconf == "N" or "No":
print "Please try again."
elif infoconf == "Y" or "Yes":
start()
else:
print "That is not a yes or no answer, please try again."
Supposed to be
infoconf = raw_input("Is this information correct? Y/N: ")
#you wrote: infoconf == "N" or "No" but should be:
if infoconf == "N" or infoconf == "No":
print "Please try again."
#you wrote: infoconf == "Y" or "Yes" but should be
elif infoconf == "Y" or infoconf == "Yes":
start()
else:
print "That is not a yes or no answer, please try again."
Short explanation:
when value of x = 'N'
x == 'N' or 'No' will return True
when value of x = 'Y'
x == 'N' or 'No' will return 'No' i believe this is not what you want
at the other side
when value of x = 'N'
x == 'N' or x == 'No' will return True
when value of x = 'Y'
x == 'N' or x == 'No' will return False i believe this is what you want
Python will interpret infoconf == "N" or "No" differently than you thought. This is somewhat a case of "operator precedence" where your condition is parsed as (infoconf == "N") or ("No").
Now, infoconf == "N" may or may not be true, but "No" is "something" and when treated as a logical evaluates as true. In effect, your condition infoconf == "N" or true will always be true.
As many others suggested, comparing infoconf to "No" in your second logical term will do the trick.
Personally I'd do something like this:
infoconf = raw_input("Is this information correct? Y/N: ")
if infoconf.lower().startswith('n'):
# No
elif infoconf.lower().startswith('y'):
# Yes
else:
# Invalid
This means that the user could reply "Y/y/yes/yeah" for yes, and "N/n/no/nah" for no.
In Python, it's a bit easier to do this as:
infoconf = raw_input("Is this information correct? Y/N: ")
if infoconf in ["N", "No"]:
print "Please try again."
elif infoconf in ["Y", "Yes"]:
start()
else:
print "That is not a yes or no answer, please try again."
As others have said, if infoconf == "N" or "No" is equivilent to if (infoconf == "N") or "No", and since "No" (as a non-empty string) evaluates to True, the statement will always be true.
Also, to be a little less picky on the input, you might want to do infoconf = infoconf.strip().lower() before you do the tests (and then compare to the lower case versions).