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.
In Python, we can use logical operators (i.e., and, or) to use multiple conditions in the same if statement. Look at the code below.
Here we'll study how can we check multiple conditions in a single if statement. This can be done by using 'and' or 'or' or BOTH in a single statement. and comparison = for this to work normally both conditions provided with should be true. If the first condition falls false, the compiler doesn't check the second one.
Test multiple conditions with a single Python if statementTo test multiple conditions in an if or elif clause we use so-called logical operators. These operators combine several true/false values into a final True or False outcome (Sweigart, 2015).
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
...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With