If Statement doesn't read input [duplicate] - python

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 5 years ago.
Just learning how to code, and wanted to make a small program to see what I know.
n = int(input("Pick a number any Number: "))
if n > 100:
print ("No... Not that Number")
else:
answer = input("Would you like to know your number?")
if answer == "Y" or "Yes" or "y" or "yes":
print ("Your number is %s" % (n))
elif answer == "N" or "No" or "n" or "no" or "NO":
print ("Oh, well that's a shame then.")
else:
print ("Please type Yes or No")
input("Press Enter/Return to Exit")
Everything works, except for the second if statement, which doesn't follow any of the data entered into input. Any reason why it does this?

Python isn't human, it doesn't understand
if answer == "Y" or "Yes"
The way you mean it to. You should do
if answer == 'Y' or answer == 'Yes'
Or even better
if answer in ('Yes', 'Y', 'yes', 'y')
Or even shorter
if answer.lower() in ('yes', 'y')

== has a higher precedence than or. So, in the if condition your're checking whether answer == 'Y' and then oring this boolean expression with "Yes", which is a non-None string, so it evaluates as True. Instead, you should use the in operator to check if answer is one of the values you're interested in:
if answer in ("Y", "Yes", "y", "yes"):
print ("Your number is %s" % (n))
elif answer in ("N", "No", "n", "no", "NO"):
print ("Oh, well that's a shame then.")
else:
print ("Please type Yes or No")

Related

Why is my if-elif-else statement always returning the same answer? [duplicate]

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

Why is this simple python program not working the way I want it to? [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 6 months ago.
The following code snippet is meant to allow the user to input the answer to a question. They are allowed to enter four
answers: either y or Y for “yes”, or n or N for “no”. The program is supposed to print out the received answer if the
entry is valid, and print out an error message otherwise.
answer = input("What is your answer? ")
if answer == "y" or "Y":
print("You answered yes")
elif answer == "n" or "N":
print("You answered no")
else:
print("You didn’t enter an acceptable answer")
It just keeps on saying that I answered yes regardless if I put n or N or some random thing. Can someone explain it to me?
The precedence of the or is not what you are expecting. Instead try:
answer = input("What is your answer? ")
if answer in ("y", "Y"):
print("You answered yes")
elif answer in ("n", "N"):
print("You answered no")
else:
print("You didn’t enter an acceptable answer")
Or maybe like:
answer = input("What is your answer? ")
if answer.lower() == "y":
print("You answered yes")
elif answer.lower() == "n":
print("You answered no")
else:
print("You didn’t enter an acceptable answer")
Your first condition will always return true because "Y" is always truthy.
Try: if answer == "y" or answer == "Y":
And the same modification for the other conditional.
If you want to check a variable shortly as you want, use something like this:
if answer in ["y","Y"]:
It will return True if answer is y or Y

Python - if statement not working correctly [duplicate]

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 8 years ago.
I've just started using python and have got stuck on something that, in my mind, clearly should work. This is my first code and I just try to have a conversation with the user.
year = input("What year are you in school? ")
yearlikedislike = input("Do you like it at school? ")
if (yearlikedislike == "yes" or "Yes" or "YES" or "yep" or "yup" or "Yep" or "Yup"):
print("What's so good about year " + year, "? ")
input("")
print("That's good!")
time.sleep(1)
endinput = input("I have to go now. See you later! ")
exit()
if (yearlikedislike == "no" or "No" or "nope" or "Nope" or "NOPE"):
print("What's so bad about year " + year, "?")
input("")
time.sleep(1)
print("Well that's not very good at all")
time.sleep(1)
endinput = input("I have to go now. See you later! ")
time.sleep(1)
exit()
My problem is that even if I reply with a negative answer it will still reply with a response as if I have said yes and if I switch the 2 around (so the code for the negative answer is above the code for the positive answer) it will always reply as if I have given a negative response.
if yearlikedislike in ("yes", "Yes", "YES", "yep", "yup", "Yep", "Yup"):
or
if yearlikedislike.lower() in ("yes","yep","yup"):
will do the trick
This is because Python is evaluating the "truthiness" of "Yes".
Your first if statement is interpreted like this:
if the variable "yearlikedislike" equals "yes" or the string literal "Yes" is True (or "truthy"), do something
You need to compare against yearlikedislike each time.
Try it like this:
if yearlikedislike in ("yes", "Yes", "YES", "yep", "yup", "Yep", "Yup"):
#do something
if (yearlikedislike == "yes" or "Yes" or "YES" or "yep" or "yup" or "Yep" or "Yup"):
Strings evaluate to True. I know you think you're saying that if yearlikedislike is equal to any of those things, keep going. However, what you're actually saying is:
if yearlikedislike equals "yes", or if "Yes" exists (which it does), or "YES" exists, etc:
What you want is either:
if (yearlikedislike == "yes" or yearlikedislike == "Yes" or yearlikedislike == "YES")
or better:
yearlikedislike in ("yes", "Yes", "YES", "yep", "yup", "Yep", "Yup")
It is because the condition is interpreted as :
if(yearlikedislike == "yes" or "Yes" == True or "YES" == True #...
try
if(yearlikedislike == "yes" or yearlikedislike == "Yes" or yearlikedislike == "YES"#...
or a more concise way :
if(yearlikedislike in ("yes", "Yes", "YES", #...
even more concise way :
if(yearlikedislike.lower() in ("yes", "yup", #...
A String (here "Yes") converted to a boolean is converted to True if it's not empty
>>> bool("")
False
>>> bool("0")
True
>>> bool("No")
True
Each part after or is independant from the previous.
Also consider using else or elif instead of two related if. And try to lower character before testing them so you need less test.

Python Input Function

I was wondering if somebody could tell me what is wrong with this code, when I run the code it shows nothing but if I take out the "elif" it does work.\
first=input("What is your first name? ");
middle=input("What is your middle name? ");
last=input("What is your last name? ");
test = [first, middle, last];
print ("");
print ("Firstname: " + test[0]);
print ("Middlename: " + test[1]);
print ("Lastname: " + test[2]);
print ("");
correct=input("This is the information you input, correct? ");
if (correct == "Yes" or "yes"):
print ("Good!")
elif (correct == "no" or "No"):
print ("Sorry about that there must be some error!");
Here's the problem:
if (correct == "Yes" or "yes"):
# ...
elif (correct == "no" or "No"):
# ...
It should be:
if correct in ("Yes", "yes"):
# ...
elif correct in ("No", "no"):
# ...
Notice that the right way to make a comparison involving several conditions is like this:
correct == "Yes" or correct == "yes"
But usually it gets written like this, which is shorter:
correct in ("Yes", "yes")
You need to use the in keyword:
if correct in ("Yes", "yes"):
print ("Good!")
elif correct in ("no", "No"):
print ("Sorry about that there must be some error!")
or convert the entire input to the same case:
# I use the lower method of a string here to make the input all lowercase
correct=input("This is the information you input, correct? ").lower()
if correct == "yes":
print ("Good!")
elif correct == "no":
print ("Sorry about that there must be some error!")
Personally, I think the lower solution is the cleanest and best. Note however that it will make your script accept inputs such as "YeS", "yEs", etc. If this is a problem, go with the first solution.
You'e checking correct incorrectly
if (correct == "Yes" or "yes"):
means (correct == "Yes") or ("yes"), and non-empty string evaluates to True in python, so first condition will always be True.If you want to check multiple strings, you can do:
if (correct in ("Yes", "yes")):
But this one doesn't takes 'yEs' or 'yES' into account. If you want case-insensitive comparison, then I think correct.lower() == "yes" would be preferred method.

If-branch for x == "N" or "No" always runs [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 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).

Categories

Resources