Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"or" conditional in Python troubles [duplicate]

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.

like image 262
Interrupt Avatar asked Jun 29 '13 01:06

Interrupt


People also ask

How do you check multiple conditions in one if statement?

Here we'll study how can we check multiple conditions in a single if statement. This can be done by using 'and' or 'or' or BOTH in a single statement. and comparison = for this to work normally both conditions provided with should be true. If the first condition falls false, the compiler doesn't check the second one.

How do you add or in an if statement in Python?

Example 1: Python If Statement with OR Operator In the following example, we will learn how to use python or operator to join two boolean conditions to form a boolean expression. today = 'Saturday' if today=='Sunday' or today=='Saturday': print('Today is off. Rest at home. ')

Can you have multiple and statements in Python?

Python supports multiple independent conditions in the same if block. Say you want to test for one condition first, but if that one isn't true, there's another one that you want to test. Then, if neither is true, you want the program to do something else. There's no good way to do that using just if and else .


1 Answers

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.

like image 59
Barmar Avatar answered Oct 09 '22 19:10

Barmar