Fix Python – Python syntax for “if a or b or c but not all of them”


Asked By – Chris Wilson

I have a python script that can receive either zero or three command line arguments. (Either it runs on default behavior or needs all three values specified.)

What’s the ideal syntax for something like:

if a and (not b or not c) or b and (not a or not c) or c and (not b or not a):


Now we will see solution for issue: Python syntax for “if a or b or c but not all of them”


If you mean a minimal form, go with this:

if (not a or not b or not c) and (a or b or c):

Which translates the title of your question.

UPDATE: as correctly said by Volatility and Supr, you can apply De Morgan’s law and obtain equivalent:

if (a or b or c) and not (a and b and c):

My advice is to use whichever form is more significant to you and to other programmers. The first means “there is something false, but also something true”, the second “There is something true, but not everything”. If I were to optimize or do this in hardware, I would choose the second, here just choose the most readable (also taking in consideration the conditions you will be testing and their names). I picked the first.

This question is answered By – Stefano Sanfilippo

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0