我正在学习Python,但遇到了一些问题。在我正在学习的课程中看到类似内容后,想出了这个简短的脚本。在成功使用之前,我已经将“或”与“ 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:
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。但是,如果这样做,它将是:
else
elif x != "monkey" and x != "monkeys"
您还记得在逻辑课上学习过的德摩根定律吗?他们解释了如何反转合取或析取。