0

can you please explain to me why this code:

if (x and y) and z > 0:
    return True

isn't the same as:

if (x and y) > 0 < z:
    return True

Basically, why cant I chain several variables like:

if var1 and var2 and var3 and var4 > 0:
    do_this

What am I doing wrong?

--edit-- I suppose I just want to know how can I shorten the condition without writing:

if var1 > 0 and var2 > 0 and var3 > 0

especially if the condition is a long one like:

if var1 > (pow(x, 3) / 2.5*pow(y,0.5)+x*y)

if would be unfeasible to rewrite the condition for every variable, imagine if I had 10 of those vars. Or is there a better way which I am not seeing that could be used in situations like this? Thanks for answers!

HamsterWithPitchfork
  • 750
  • 1
  • 12
  • 21

1 Answers1

5

This isn't doing what you imagine:

if (x and y) > 0 < z: return True

The above evaluates (x and y) first, if both are truthy then y is returned, so now we have:

if y > 0 < z: return True

Which is the same as:

if y > 0 and 0 < z

Clearly, the above isn't the same as the other expression:

if (x and y) and z > 0: return True
if y and z > 0:
if z > 0:

Bottom line: (x and y) > 0 is definitely not doing what you imagine! what you meant to say must be written like this:

 if x > 0 and y > 0 and z > 0: return True
Óscar López
  • 232,561
  • 37
  • 312
  • 386
  • Thanks for the explanation! Is there any way to shorten the expression? Without rewriting x > 0 and y > 0 and z > 0? So it checks if every listed variable is > 0? – HamsterWithPitchfork Feb 17 '14 at 07:49
  • @metacore there isn't a general solution for comparing multiple values at once. For this case in particular, the expression in the last line of my answer is the simplest way to express the condition – Óscar López Feb 17 '14 at 13:55