I'm wondering what are the rules to write conditions in Python. I'm quite new to Python. I come from C and I'm used to set brackets around conditions, which doesn't seem to be the rule in Python.
I was trying to set a condition on a while loop and I encountered a problem, here is my initial code:
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.
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 ? from left to right ?
does it interprete valid_rx is False, then False & retry, then 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 ...
If someone has a clear explanation (or reference) I would be interested.
3 Answers 3
& is not considered as AND condition in Python. You have to use and.
valid_rx = False
retry = 0
while valid_rx is False and retry < 5:
print("hello")
Comments
You should use the logical short-circuit operator and, not the bitwise operator &.
Also note that the boolean valid_rx can be used directly in your condition; more concise:
while not valid_rx and retry < 5:
...
Comments
>>> valid_rx = False
>>> retry = 0
>>> not valid_rs and retry < 5
use not, and. Python is said to be "runnable pseudocode".