Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple logical comparisons on a single line for an if statement

Tags:

python

I want to do multiple comparisons for a logical condition in python but I am not sure of the right way round for the and and or. I have 2 statements.

Statement 1:

#if PAB is more than BAC and either PAB is less than PAC or PAC is more than BAC
if PAB > BAC and PAB< PAC or PAB > BAC and PAC>BAC: 

Statement 2:

#if PAB is more than BAC and PAC is less than PAB or if PAB is less than BAC and PAC is less than BAC
if PAB >BAC and  PAC<PAB or PAB<BAC and  PAC<BAC

Is or-ing the two ands the correct way to go about it?

Thanks.

like image 857
mark mcmurray Avatar asked May 07 '13 16:05

mark mcmurray


1 Answers

Looking at statement 1, I'm assuming you mean:

if (PAB > BAC and PAB< PAC) or (PAB > BAC and PAC>BAC): 

In which case, I'd probably write it like this (using chained comparisons, docs: python2, python3):

if (BAC < PAB < PAC) or min(PAB,PAC)>BAC:

You can use an analogous form for statement 2.

Having said that, I cannot make your comments in the question's code match up with my interpretation of your conditionals, so it's plausible I don't understand your requirement.

like image 86
David Heffernan Avatar answered Oct 26 '22 19:10

David Heffernan