if / elif语句的多个条件 [英] Multiple conditions with if/elif statements
问题描述
我正在尝试从多个条件触发if语句,而不使用不同的触发器多次重写语句。例如:
I'm trying to get an if statement to trigger from more than one condition without rewriting the statement multiple times with different triggers. e.g.:
if user_input == "look":
print description
if user_input == "look around":
print description
你会如何压缩这些是一个声明吗?
How would you condense those into one statement?
我尝试过使用'或',无论输入是否匹配任何条件,它都会导致任何raw_input触发语句。
I've tried using 'or' and it caused any raw_input at all to trigger the statement regardless of whether the input matched either of the conditions.
if user_input == "look" or "look around":
print description
推荐答案
你要做的是
if user_input == "look" or user_input == "look around":
print description
如果你有很多可能性,另一个选择是:
Another option if you have a lot of possibilities:
if user_input in ("look", "look around"):
print description
既然你'使用2.7,你也可以这样写(它适用于2.7或3+,但不适用于2.6或更低版本):
Since you're using 2.7, you could also write it like this (which works in 2.7 or 3+, but not in 2.6 or below):
if user_input in {"look", "look around"}:
print description
这使得 设置
元素,搜索速度稍快结束(尽管这只在你检查的元素数量远大于2时才有意义。)
which makes a set
of your elements, which is very slightly faster to search over (though that only matters if the number of elements you're checking is much larger than 2).
你第一次尝试总是经历的原因是这个。 Python中的大多数内容评估为 True
(除了 False
,无
,或空字符串,列表,dicts,...)。 或
接受两件事并将其评估为布尔值。所以 user_input ==look或环顾四周
被视为(user_input ==look)或look_around
;如果第一个是假的,那就像你写了,如果look_around:
,它将永远通过。
The reason your first attempt always went through is this. Most things in Python evaluate to True
(other than False
, None
, or empty strings, lists, dicts, ...). or
takes two things and evaluates them as booleans. So user_input == "look" or "look around"
is treated like (user_input == "look") or "look_around"
; if the first one is false, it's like you wrote if "look_around":
, which will always go through.
这篇关于if / elif语句的多个条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!