-1

I was not able to find proper documentation about it. Same thing I did in Javascript and I got False for Both Cases. I know that 3>2 should be treated as (3>2) -> True|1, therefore 3>2>1 is 1>1 which is false. It would be great if you could suggest some official documentation along with the explanation.

x = (3 > 2) > 1

print(x)

False

y = 3 > 2 > 1

print(y)

True

echo
  • 86
  • 7

2 Answers2

5

Javascript is evaluating 3 > 2 > 1 as (3 > 2) > 1, so they are equivalent. In both cases, 3 > 2 > 1 -> true > 1 -> false.

Python, however, features comparison chaining, so 3 > 2 > 1 means 3 > 2 and 2 > 1. (3 > 2) > 1 works the same way it does in JS. Here's an article you can read to learn more. Here's a high-quality answer on this site that explains the difference between operator grouping and chaining in python.

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
thisisrandy
  • 2,660
  • 2
  • 12
  • 25
0

The reason why 3>2>1 returns True whereas (3>2)>1 returns False in Python is because of the way that the comparison operators work in Python.

In the first example, 3>2>1, Python is interpreting this as (3>2) and (2>1). The first comparison 3>2 returns True, which is then compared to 2>1 which also returns True. Since both comparisons are True, the overall expression evaluates to True.

In the second example, (3>2)>1, Python is interpreting this as True>1. The comparison True>1 returns False as true is considered 1 and 1 is not greater than 1.

In Python, comparison operators return a Boolean value, True or False, rather than an integer value. When a Boolean value is used in a numeric context, such as a comparison, True is interpreted as 1 and False is interpreted as 0 , that's why the second example return False.