Monday, February 4, 2019

"or" conditional in Python troubles




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.


Answer



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.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...