How to use comparison operators in Python
Get to know Comparison operators
The following table lists the comparison operators in Python.
Operator | Description |
---|---|
X < Y | less than |
X <= Y | Less than or equal to |
X > Y | greater than |
X >= Y | Greater than or equal to |
X == Y | Equal to (same value) |
X != Y | Not equal to |
X is Y | Same object |
X is not Y | Negated object identity |
X < Y < Z | Chained comparisons |
x in y | x is a member of the container (e.g., sequence) y. |
x not in y | x is not a member of the container (e.g., sequence) y. |
Standard comparison operators return a Boolean value indicating the truthfulness of the expression.
print 2 < 4# w w w.j a v a2 s . co m
print 2 == 4
print 2 > 4
print 6.2 <= 6
print 6.2 <= 6.2
print 6.2 <= 6.20001
print 2 == 2
print 2.46 <= 8.33
print 5+4j >= 2-3j
The code above generates the following result.
Compare integers using if structures, relational operators and equality operators.
# read string and convert to integer
number1 = raw_input( "Please enter first integer: " )
number1 = int( number1 )# w w w . j av a 2 s.com
number2 = raw_input( "Please enter second integer: " )
number2 = int( number2 )
if number1 == number2:
print "%d is equal to %d" % ( number1, number2 )
if number1 != number2:
print "%d is not equal to %d" % ( number1, number2 )
if number1 < number2:
print "%d is less than %d" % ( number1, number2 )
if number1 > number2:
print "%d is greater than %d" % ( number1, number2 )
if number1 <= number2:
print "%d is less than or equal to %d" % ( number1, number2 )
if number1 >= number2:
print "%d is greater than or equal to %d" % ( number1, number2 )
The code above generates the following result.
multiple comparisons can be made on the same line, evaluated in left-to-right order
print 3 < 4 < 7 # same as ( 3 < 4 ) and ( 4 < 7 )
print 4 > 3 == 3 # same as ( 4 > 3 ) and ( 3 == 3 )
print 4 < 3 < 5 != 2 < 7
The code above generates the following result.
Comparing Strings and Sequences
Strings are compared according to their order when sorted alphabetically:
print "alpha" < "beta"
The code above generates the following result.
To ignore the difference between uppercase and lowercase letters, use the string methods upper or lower:
print 'python'.lower() == 'Python'.lower()
The code above generates the following result.
Other sequences are compared in the same manner, except that instead of characters you may have other types of elements:
print [1, 2] < [2, 1]
The code above generates the following result.
If the sequences contain other sequences as elements, the same rule applies to these sequence elements:
# w w w . ja v a 2 s. c o m
print [2, [1, 4]] < [2, [1, 5]]
print 'abc' == 'xyz'
print 'abc' > 'xyz'
print 'abc' < 'xyz'
print [3, 'abc'] == ['abc', 3]
print [3, 'abc'] == [3, 'abc']
The code above generates the following result.