Reputation: 632
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 pass/continue, but if only one of the variables are 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 don't think this example will work the way I would want it as my understanding of OR is 1 condition returns True or both conditions return True. If someone could assit in pointing me in the right direction, it would greatly be apprecaited.
Upvotes: 12
Views: 25953
Reputation: 3334
This method is technically slower because it has to calculate the comparisons twice, but I find it slightly 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.
Upvotes: 3
Reputation: 5533
Just another way of doing so:
if max(ht1, ht2) > 0.05 and min(ht1, ht2) <= 0.05:
Upvotes: 0
Reputation: 47770
What you want is called an "exclusive-OR", which in this case can be expressed as a 'not-equal' or 'is not' relation:
if (ht <= 0.05) is not (ht2 <= 0.05):
The way this works is that the if
will only succeed if one of them is True
and the other one is False
. If they're both True
or both False
then it'll go to the else
block.
Upvotes: 18
Reputation: 798536
Since relational operators always result in a bool
, just check to see if they are different values.
if (ht1 <= 0.05) != (ht2 <= 0.05): # Check if only one is true
...
Upvotes: 9