Comparison Operators¶
Comparison operators are used to compare the values of two objects. For example, you might want to compare
is
a
equal tob
:a == b
is
a
not equal tob
:a != b
is
a
greater thanb
:a > b
is
a
less thanb
:a < b
is
a
greater than or equal tob
:a >= b
is
a
less than or equal tob
:a <= b
==
operator¶
First we will learn how to check if two things are equal
in Python. To do this we use the operator ==
.
When comparing two objects with ==
, it will return
True
if the two values are equal otherwise it will return
False
. Here are some examples. Notice that the return type
of each expression is a Boolean data type (True
or False
).
1 == 1
True
1 == 2
False
'hello world' == 'hello world'
True
'Hello world' == 'hello world' # not the same string because capital H on the left
False
a = 'string'
b = 10
a == b
False
a = 5
b = 6
c = 3
d = 14
print(a + b)
print(d - c)
print(a + b == d - c)
11
11
True
str1 = "a b c d e f"[::2] # from index 0 to end with a stride of 2
print(str1)
str2 = "a b c d e f"[0::3] # from index 0 to end with a stride of 3
print(str1)
# str1 and str1 are the same value
str1 == str2
abcdef
abcdef
True
True == False # they are not equal so returns False
False
True == True
True
False == False
True
!=
operator¶
The operator !=
checks if two things
are not equal. It returns True
if they
are not equal and False
otherwise.
1 != 1
False
True != False
True
True != True
False
False != False
False
str(40) + str(40) != 4040
True
str(40) + str(40) != '4040'
False
40 + 40 != 80
False
40 + 40 != '80'
True
3.14 != 6.28 / 2
False
>
operator¶
This is the greater than operator: >
.
It returns True
if the value on the left
is greater than the value on the right.
Otherwise it returns False
.
2 > 1 # yes, 2 is greater than 1
True
1 > 2 # no, 1 is not greater than 2
False
2 > 2
False
0 > -2
True
-2 > -5 + 4
False
<
operator¶
This is the less than operator: <
.
It returns True
if the value on the left
is less than the value on the right.
Otherwise it returns False
.
2 < 1 # no, 2 is not less than 1
False
1 < 2 # yes, 1 is less than 2
True
2 < 2
False
0 < -2
False
-2 < -5 + 4
True
>=
operator¶
This is the greater than or equal to operator: >=
.
It returns True
if the value on the left
is greater than or equal to the value on the right.
Otherwise it returns False
.
5 >= 5
True
5 >= 3
True
<=
operator¶
This is the less than or equal to operator: <=
.
It returns True
if the value on the left
is less than or equal to the value on the right.
Otherwise it returns False
.
-2 <= -2
True
-2 <= -1
True