【问题标题】:"or" conditional in Python troubles [duplicate]Python问题中的“或”条件[重复]
【发布时间】:2013-06-26 21:09:12
【问题描述】:

我正在学习 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。

【问题讨论】:

    标签: python conditional-statements conditional-operator


    【解决方案1】:

    大多数编程语言中的布尔表达式不遵循与英语相同的语法规则。您必须对每个字符串进行单独比较,并将它们与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吗?他们解释了如何反转连词或析取词。

    【讨论】:

    • 非常感谢您提供的有用信息和很棒的信息,现在帮助我更好地掌握它!
    【解决方案2】:

    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
    

    【讨论】:

    • 非常酷,我什至不知道运算符中的那个。谢谢
    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-20
      • 2014-04-13
      • 1970-01-01
      • 2014-12-07
      • 2014-01-28
      • 2013-06-20
      • 2013-09-14
      相关资源
      最近更新 更多