简体   繁体   English

Python:如何表达更少或相等,更大的环境?

[英]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 to x < y and y <= z , except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be False ). 比较可以任意链接,例如, x < y <= z等于x < y and y <= z ,除了y仅被评估一次(但在两种情况下,当x < y被发现时,根本不评估zFalse )。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM