简体   繁体   English

用Python编写条件的方式

[英]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. 如果有人有明确的解释(或参考),我将很感兴趣。

& is not considered as AND condition in Python. &在Python中不被视为AND条件。 You have to use and . 您必须使用and

valid_rx = False
retry = 0

while valid_rx is False and retry < 5:
    print("hello")

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.

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