带有两个字符串的if语句
我刚开始学习Python,想练习一下if语句,因为我在玩文字冒险游戏。我想让一个功能正常工作。例如,如果有人输入“看地板”(或者简单点说“看地”),那么word1就应该是'看',word2就是'地板'。
也许这个问题有简单的解决办法,我试过几种不同的方法,但就是没法让它正常工作。谢谢大家的帮助!
def test():
answer = raw_input().lower()
if ('word1' and 'word2') in answer:
print "Both words were in the answer."
else:
print "Both words were NOT in the answer"
test()
4 个回答
其他的回答都不错,但我来帮你解释一下你的逻辑哪里出错了:
if ('word1' and 'word2') in answer:
根据Python的运算顺序规则,你在if
语句中括号里的内容会先被计算。
所以,实际上你的表达式被解释器理解为:
temp = ('word1' and 'word2')
if temp in answer:
print "Both words were in the answer."
上面的temp
的值是通过逻辑and
把两个不同的字符串结合在一起,这样做其实没有太大意义。在这种情况下,如果第一个操作数的结果是True
,那么第二个操作数就会被返回;如果第一个操作数是False
(比如一个空字符串),Python就会返回第一个操作数。因此在你的具体情况下,Python只会返回第二个字符串,所以:
('word1' and 'word2') == 'word2'
因此,解释器把你的代码理解为:
if ('word2') in answer:
print "Both words were in answer."
通过这样写:
if ('word1' in answer) and ('word2' in answer):
print "Both words were in answer."
你把想要比较的内容明确写出来,这样解释器就能理解,不会给你奇怪的结果。
你可以使用all
来实现这个功能:
def test():
answer = raw_input().lower()
if all(word in answer for word in ('word1', 'word2')):
print "Both words were in the answer."
else:
print "Both words were NOT in the answer"
test()
这个方法会检查你指定的每一个单词,看看它们是否都在answer
里面。内置的函数all()
会在所有检查都通过时返回True
,如果有任何一个检查没有通过,它就会返回False
。换句话说,只有在所有检查都为True
的时候,结果才会是True
。
这里有个更详细的解释:
评估顺序!
你需要记住,虽然一些常见的表达方式在英语(或其他语言)中很有意义,但在编程语言中可能就不那么好理解了,即使它的语法是正确的。
比如,我们来看一下你示例代码中的测试表达式:
('word1' and 'word2') in answer
当你应用评估顺序的规则时,括号里的子表达式( ('word1' and 'word2')
)会首先被计算。由于使用了 and
运算符,这个子表达式的结果是右边的操作数,因为左边的操作数计算结果为 True
。把这个结果放回你最初的表达式中,就变成了 'word2' in answer
。因此,只要第二个单词能在答案中找到,测试就总是会通过。
编辑:修正了布尔值的评估。