Python 针对字符串的多个布尔值
我正在尝试再次检查用户输入字符串中的多个单词:Python 针对字符串的多个布尔值,python,formatting,boolean,Python,Formatting,Boolean,我正在尝试再次检查用户输入字符串中的多个单词: prompt = input("What would you like to know?") if ('temperature' and 'outside') in prompt: 起初我试图对照“室外”和(“温度”或“天气”)进行检查,但我在两方面都遇到了相同的问题。如果我只输入'temperature',代码不会返回true,但如果我只输入'outside',它会返回true 是否有一段格式我遗漏了,让它检查两个文本值,而不仅仅是一个 您看到
prompt = input("What would you like to know?")
if ('temperature' and 'outside') in prompt:
起初我试图对照“室外”
和(“温度”或“天气”)
进行检查,但我在两方面都遇到了相同的问题。如果我只输入'temperature'
,代码不会返回true
,但如果我只输入'outside'
,它会返回true
是否有一段格式我遗漏了,让它检查两个文本值,而不仅仅是一个 您看到的意外行为的原因是
和在这里具有更高的优先级;这是因为
中的只能在左侧有一个表达式
所以发生的是“温度”和“外部”
被评估。和
的语义是这样的:如果其左侧操作数为truthy(且所有非空字符串均为truthy),则整个表达式的值将等于右侧操作数(在本例中,“外部”
):
因此,您所做的操作相当于在提示符中检查是否为“外部”
相反,您可以:
if 'temperature' in prompt and 'outside' in prompt:
...
或者更一般地说:
words = ['temperature', 'outside']
if all(word in prompt for word in words):
...
要结合各种条件:
words = ['temperature', 'weather']
if 'outside' in prompt and any(word in prompt for word in words):
...
您没有包含语言标记;是Python吗?如果没有,请添加相应的标签
words = ['temperature', 'weather']
if 'outside' in prompt and any(word in prompt for word in words):
...