I’m learning Python and I’m having a little bit of a problem. Came up with this short script after seeing something similar in a course I’m taking. I’ve used “or” with “if” before with success (it doesn’t show much here). For some reason I can’t seem to get this working:
test = raw_input("It's the flying circus! Cool animals but which is the best?")
x = test.lower()
if x == "monkey" or "monkeys":
print "You're right, they are awesome!!"
elif x != "monkey" or "monkeys":
print "I'm sorry, you're incorrect.", x[0].upper() + x[1:], "is not the right animal."
But this works great:
test = raw_input("It's the flying circus! Cool animals but which is the best?")
x = test.lower()
if x == "monkey":
print "You're right, they are awesome!!"
elif x != "monkey":
print "I'm sorry, you're incorrect.", x[0].upper() + x[1:], "is not the right animal."
Probably the or conditional does not fit here. But I’ve tried and, etc. I’d love a way to make this accept monkey or monkeys and everything else triggers the elif.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Boolean expressions in most programming languages don’t follow the same grammar rules as English. You have to do separate comparisons with each string, and connect them with or:
if x == "monkey" or x == "monkeys":
print "You're right, they are awesome!!"
else:
print "I'm sorry, you're incorrect.", x[0].upper() + x[1:], "is not the right animal."
You don’t need to do the test for the incorrect case, just use else. But if you did, it would be:
elif x != "monkey" and x != "monkeys"
Do you remember learning about deMorgan’s Laws in logic class? They explain how to invert a conjunction or disjunction.
Method 2
gkayling is correct. Your first if statement returns true if:
x == “monkey”
or
“monkeys” evaluates to true (it does since it’s not a null string).
When you want to test if x is one of several values, it’s convenient to use the “in” operator:
test = raw_input("It's the flying circus! Cool animals but which is the best?")
x = test.lower()
if x in ["monkey","monkeys"]:
print "You're right, they are awesome!!"
else:
print "I'm sorry, you're incorrect.", x[0].upper() + x[1:], "is not the right
Method 3
Should be
if x == "monkey" or x == "monkeys":
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0