1

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.

Arpit Solanki
10k4 gold badges45 silver badges57 bronze badges
asked Sep 1, 2017 at 8:38

3 Answers 3

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")
Ma0
15.2k4 gold badges38 silver badges70 bronze badges
answered Sep 1, 2017 at 8:42
Sign up to request clarification or add additional context in comments.

Comments

3

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:
 ...
bruno desthuilliers
78.3k6 gold badges103 silver badges129 bronze badges
answered Sep 1, 2017 at 8:43

Comments

0
>>> valid_rx = False
>>> retry = 0
>>> not valid_rs and retry < 5

use not, and. Python is said to be "runnable pseudocode".

answered Sep 1, 2017 at 8:43

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.