3

I'm newbie in python. I have a three variables x, y, z as a int. I have comparison three variables in if condition. I'm confused about following code result.

The expression x < y <= z evaluates to false.

Let's assume x = 10, y = 5 and z = 0. if x < y become False, then False <= 0 become True. but output is False. Why?

My python script:

#!/usr/bin/python

x = 10
y = 5
z = 0

if (x < y < z):
        print"True"
else:
        print"False"
msc
  • 33,420
  • 29
  • 119
  • 214
Jayesh
  • 4,755
  • 9
  • 32
  • 62

2 Answers2

3

The document say:

Comparisons can be chained arbitrarily; for example, x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false).

x < y <= z neither means (x < y) <= z nor x < (y <= z). x < y <= z is equivalent to x < y and y <= z, and is evaluates from left-to-right.

Logical AND do not have associativity in Python unlike C and C++. There are separate rules for sequences of this kind of operator and cannot be expressed as associativity.

x < y and y <= z only evaluates the second argument if the first one is true because and is a short-circuit operator.

msc
  • 33,420
  • 29
  • 119
  • 214
1

That expression is evaluated as:

if (x < y and y < z):
    pass

So now you see why it is false is because x is not less than y

smac89
  • 39,374
  • 15
  • 132
  • 179