Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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.

like image 754
TsvGis Avatar asked Sep 24 '15 04:09

TsvGis


People also ask

Can you have two conditions in an if statement Python?

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.

How do you check multiple conditions in one if statement?

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.

Can you have 3 conditions in an if statement Python?

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).


2 Answers

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
   ...
like image 149
Ignacio Vazquez-Abrams Avatar answered Oct 05 '22 02:10

Ignacio Vazquez-Abrams


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.

like image 44
tzaman Avatar answered Oct 05 '22 02:10

tzaman