Python conditional one or the other but not both

I am trying to compile an if statement in python where it checks two variables to see if they are <= .05. Now, if both variables are True, I just want the code to go through / continue, but if only one of the variables is True, then I want the code to do something. eg:

ht1 = 0.04 ht2 = 0.03 if (ht1 <= 0.05) or (ht2 <= 0.05): # do something else: pass 

I do not think that this example will work as I would like, since my understanding of OR is equal to 1 True condition or both conditions return True. If someone could persuade me to point me in the right direction, that would be very grateful.

+5
source share
4 answers

What you want is called exclusive-OR, which in this case can be expressed as an uneven or not relationship:

 if (ht <= 0.05) is not (ht2 <= 0.05): 

How it works, since if will only succeed if one of them is True and the other is False . If they are both True or both False , then they will go to the else block.

+8
source

Since relational operators always lead to bool , just check to see if they are different values.

 if (ht1 <= 0.05) != (ht2 <= 0.05): # Check if only one is true ... 
+7
source

This method is technically slower because it has to calculate comparisons twice, but I find it more readable. Your mileage may vary.

 ht1 = 0.04 ht2 = 0.03 if (ht1 <= 0.05) and (ht2 <= 0.05): pass elif (ht1 <= 0.05) or (ht2 <= 0.05): # do something. 
+3
source

Another way to do this:

 if max(ht1, ht2) > 0.05 and min(ht1, ht2) <= 0.05: 
0
source

Source: https://habr.com/ru/post/1232161/


All Articles