Skip to main content
 首页 » 编程设计

python之带有两个字符串的 If 语句

2025年05月04日16lyj

我刚开始学习 Python,并且想练习一下 if 语句,因为我正在玩文字冒险游戏。我试图让这样的事情发挥作用。例如,如果输入“看地板”(或只是“看地板”),则 word1 将是“看”和“地板”。

也许对此有一个简单的答案,我已经尝试了几种不同的方法,但似乎无法让它发挥作用。感谢您的帮助!

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() 

请您参考如下方法:

您需要对每个词进行in 成员资格测试:

if ('word1' in answer) and ('word2' in answer): 

当然,如果您有很多单词,这很快就会变得乏味。在这种情况下,您可以使用 all和一个 generator expression :

if all(word in answer for word in ('word1', 'word2', ...)): 

上面的代码将测试元组 ('word1', 'word2', ...) 中的每个单词是否都可以在 answer 中找到。