Python 中的“或”条件问题[重复]

2024-02-05

我正在学习Python,但遇到了一些问题。在我正在学习的课程中看到类似的内容后,我想出了这个简短的脚本。我之前已经成功地使用了“or”和“if”(这里没有显示太多)。由于某种原因,我似乎无法让它工作:

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。


大多数编程语言中的布尔表达式并不遵循与英语相同的语法规则。您必须对每个字符串进行单独比较,然后将它们连接起来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"

你还记得学习过德摩根定律 http://en.wikipedia.org/wiki/De_Morgan%27s_laws在逻辑课上?他们解释了如何反转合取或析取。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python 中的“或”条件问题[重复] 的相关文章

随机推荐