The Python Oracle

Python conditional one or the other but not both

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Realization

--

Chapters
00:00 Question
00:50 Accepted answer (Score 17)
01:19 Answer 2 (Score 9)
01:37 Answer 3 (Score 3)
01:59 Answer 4 (Score 0)
02:12 Thank you

--

Full question
https://stackoverflow.com/questions/3275...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #ifstatement #conditional

#avk47



ACCEPTED ANSWER

Score 18


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.




ANSWER 2

Score 9


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



ANSWER 3

Score 3


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.



ANSWER 4

Score 0


Just another way of doing so:

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