Python - Number Comparisons: Normal and Chained

Introduction

Numbers can also be compared.

Normal comparisons work for numbers exactly as you'd expect.

Demo

print( 1 < 2 )                  # Less than 
print( 2.0 >= 1 )               # Greater than or equal: mixed-type 1 converted to 1.0 
print( 2.0 == 2.0 )             # Equal value 
print( 2.0 != 2.0 )             # Not equal value
# from w ww . j a va 2 s .  c  om

Result

Python allows us to chain multiple comparisons together to perform range tests.

Chained comparisons are a shorthand for larger Boolean expressions.

For example, the expression (A < B < C) tests whether B is between A and C.

It is equivalent to the Boolean test: A < B and B < C.

For example, assume the following assignments:

Demo

X = 2 
Y = 4 # from   w  w w  . j a  va  2  s  .c  o  m
Z = 6 

print( X < Y < Z )              # Chained comparisons: range tests 
print( X < Y and Y < Z )
print( X < Y > Z )
print( X < Y and Y > Z )
print( 1 < 2 < 3.0 < 4 )
print( 1 > 2 > 3.0 > 4 )

Result