Python问题中的“or”条件

2024-05-29 10:49:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我在学Python,我有点问题。在我正在上的一门课上看到类似的东西之后,我想出了这个小剧本。我以前用过“如果”或“如果”来表示成功(这里没有显示多少)。出于某种原因,我似乎无法让这个工作:

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."

但这很有效:

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."

这里可能不适合or条件。但是我试过了,等等。我想用一种方法让它接受猴子或者猴子,其他一切都会触发elif。


Tags: orthetestrightreinputrawis
3条回答

应该是 if x == "monkey" or x == "monkeys":

gkayling是对的。如果出现以下情况,则第一个if语句返回true:

x=“猴子”

或者

“monkeys”的计算结果为true(因为它不是空字符串)。

当您想测试x是否是几个值之一时,使用“in”运算符很方便:

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

大多数编程语言中的布尔表达式不遵循与英语相同的语法规则。必须对每个字符串分别进行比较,并使用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."

不需要对不正确的情况进行测试,只需使用else。但如果你做到了,那就是:

elif x != "monkey" and x != "monkeys"

你还记得在逻辑课上学过deMorgan's Laws吗?他们解释如何颠倒连接或分离。

相关问题 更多 >

    热门问题