[英]Pythonic way to write conditions
I'm wondering what are the rules to write conditions in Python. 我想知道在Python中编写条件的规则是什么。 I'm quite new to Python.
我对Python很陌生。 I come from C and I'm used to set brackets around conditions, which doesn't seem to be the rule in Python.
我来自C语言,习惯于在条件周围设置方括号,这在Python中似乎不是规则。
I was trying to set a condition on a while loop and I encountered a problem, here is my initial code: 我试图在while循环上设置条件,但遇到问题,这是我的初始代码:
valid_rx = False
retry = 0
while valid_rx is False & retry < 5:
# the rest of the code is not particularly relevant, if a failure occurs, I relaunch my attempt and increment retry
And it never executed the rest of the code. 而且它从不执行其余的代码。
I thought my condition was never True, so I tried several combinations and putting brackets around valid_rx is False
or around retry < 5
worked properly. 我以为我的情况永远不会是True,所以我尝试了几种组合,并在
valid_rx is False
周围valid_rx is False
括号valid_rx is False
或在retry < 5
周围工作正常。 I wanted to know why the initial condition failed, so in a terminal I tried the combinations, and I also tried the following: 我想知道为什么初始条件失败,所以在终端机中尝试了组合,还尝试了以下操作:
In [48]: False & retry
Out[48]: 0
Does that mean that in my initial condition this part of the condition was interpreted first ? 这是否意味着在我的初始条件中,首先要解释条件的这一部分? How does Python processes such a condition ?
Python如何处理这种情况? from left to right ?
从左到右 ? does it interprete
valid_rx is False
, then False & retry
, then retry < 5
? 它会解释
valid_rx is False
,然后valid_rx is False
False & retry
,然后retry < 5
吗? Actually I would have expected that an asserted condition would be discarded for further evaluation (ie. evaluation of valid_rx is False
would have prevented False & retry
from being interpreted) which would have made my initial condition correct ... 实际上,我
valid_rx is False
希望断言的条件将被丢弃以进行进一步评估(即, valid_rx is False
评估valid_rx is False
会阻止False & retry
被解释),这会使我的初始条件正确无误。
If someone has a clear explanation (or reference) I would be interested. 如果有人有明确的解释(或参考),我将很感兴趣。
You should use the logical short-circuit operator and
, not the bitwise operator &
. 您应该使用逻辑短路运营商
and
,而不是位运算符&
。
Also note that the boolean valid_rx
can be used directly in your condition; 还要注意,布尔值
valid_rx
可以直接在您的条件下使用; more concise: 更简洁:
while not valid_rx and retry < 5:
...
>>> valid_rx = False
>>> retry = 0
>>> not valid_rs and retry < 5
use not
, and
. not
使用and
。 Python is said to be "runnable pseudocode". 据说Python是“可运行的伪代码”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.