“or” conditional in Python troubles [duplicate]

ぐ巨炮叔叔 提交于 2019-11-27 05:10:13

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.

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

Should be if x == "monkey" or x == "monkeys":

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!