VN1992
VN1992

Reputation: 131

Python "and" and "or" if statement

In Python is it possible for me to code this and have it work as intended?

if a != None and b == None or a == None and b != None

basically I want to see if either a or b is None while the other isn't

Upvotes: 0

Views: 124

Answers (2)

Bill Lynch
Bill Lynch

Reputation: 81936

Since it sounds like you want an xor...

if (a is None) != (b is None):
    ...

Upvotes: 8

thefourtheye
thefourtheye

Reputation: 239493

In Python, there can be only one instance of NoneType can exist, so you can use is operator, like this

if (a is None and b is not None) or (b is None and a is not None):

You can also count the number of Nones like this

if (a, b).count(None) == 1:

Or you can explicitly check that like this

if a != b and (a is None or b is None):

Upvotes: 1

Related Questions