如果'z'中的'x'和'y':

tkb*_*kbx 3 python if-statement

我正在python中编写一个Q&A脚本.它获取raw_input,并将其设置为问题.我试过了if 'var1' and 'var2' in theQuestion:,但它找到的是字符串,而不是两者.有没有办法让我在一个'if'语句中完成这项工作?(不是'if x:if y:then z).

phi*_*hag 13

and是逻辑的AND,而不是自然语言.因此,您的代码被解释为:

'var1' and 'var2' in theQuestion
True   and 'var2' in theQuestion # Since bool('var1') == True
           'var2' in theQuestion
Run Code Online (Sandbox Code Playgroud)

您希望使用逻辑AND连接两个测试:

if 'var1' in theQuestion and 'var2' in theQuestion:
Run Code Online (Sandbox Code Playgroud)

或者,对于大量测试:

if all(k in theQuestion for k in ('var1', 'var2')):
Run Code Online (Sandbox Code Playgroud)

  • 或者,更一般地说,`if all(var in the var in vars)``vars`在这种情况下是`(var1,var2)`. (6认同)