[英]Python: How to express less or equal, equal greater, environment?
I want to do the following example in python: 我想在python中执行以下示例:
x = 10
y = 8
if x-5 <= y <= x+5:
print(y)
I see that this is working, but I would like to know if it's "ok" like this, if there is a better solution or something I have to consider doing it like this. 我知道这是有效的,但我想知道它是否“好”,如果有更好的解决方案,或者我必须考虑这样做。
Chained expressions are acceptable in Python: 链式表达式在Python中是可以接受的:
Comparisons can be chained arbitrarily, eg,
x < y <= z
is equivalent tox < y and y <= z
, except thaty
is evaluated only once (but in both casesz
is not evaluated at all whenx < y
is found to beFalse
).比较可以任意链接,例如,
x < y <= z
等于x < y and y <= z
,除了y
仅被评估一次(但在两种情况下,当x < y
被发现时,根本不评估z
是False
)。
In fact, because and
is lazy and the syntax is cleaner, they are preferable . 事实上,因为
and
懒惰且语法更清晰,所以它们更可取 。
Just be aware that chained expressions take priority. 请注意链接表达式优先。 For example, see Why does the expression 0 < 0 == 0 return False in Python?
例如,请参阅为什么表达式0 <0 == 0在Python中返回False? .
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.