0

I am checking wether one of two conditions applies and only one.

My question is if there is a way to have a single if statement to do this:

if x == True:
    if y == False:
        do_something()
elif x == False:
    if y == True:
        do_something()

Ideally similar to how and and or work so that it would something like:

enter code here
if x == True ° y == True:
    do_something()

whereas ° is the wanted operator

  • do nothing if: x,y = True or x,y = False
  • do something if: x = True and y = False or x = False and y = True

I would appreciate any advice if this is not possible.

Thank you in advance!!

wjandrea
  • 28,235
  • 9
  • 60
  • 81
klnstngr
  • 15
  • 4
  • because you are checking for x and y, you want to make sure x and y are not the same. The only way it is true is if x != y. So check for it and you have your answer – Joe Ferndz Jan 17 '21 at 23:36
  • Sidenote, comparing against booleans is generally bad practice. See [PEP 8](https://www.python.org/dev/peps/pep-0008/#programming-recommendations:~:text=Don't%20compare%20boolean%20values%20to%20True%20or%20False%20using%20%3D%3D%3A) and [this answer](https://stackoverflow.com/a/9494887/4518341). Instead of `if x == True` and `if x == False`, simply use `if x` and `if not x`. – wjandrea Jan 17 '21 at 23:50

1 Answers1

1

You need to use the logical operator XOR, but in this scenario, it's the equivalent of just saying

if x != y: 
   do_something()

As it will only be true if one of the conditions is met.

-- update --

There's also an actual XOR operator

if x ^ y:
   do_something()

They will be identical in this example.

Rich S
  • 3,248
  • 3
  • 28
  • 49