Comparison Operators in Python

Comparison operators are used to compare two values.

They always return a Boolean value:

1. == (Equal to)

The equal to (==) operator checks if the values on both sides are equal.

Example:

Python

a = 10
b = 10
c = 20

print(a == b)   # True → because 10 equals 10
print(a == c)   # False → because 10 is not equal to 20 

The output of the above code is shown below:

True
False 

Returns: True if equal, else False.

2. != (Not equal to)

The not equal to operator checks if the values on both sides are not equal.

Example:

Python

a = 10
b = 20
c = 10

print(a != b)   # True → because 10 is not equal to 20
print(a != c)   # False → because 10 equals 10 

The output of the above code is shown below:

True
False 

Returns: True if not equal, else False.

3. > (Greater than)

The greater than operator checks if the left value is greater than the right value.

Example:

Python

a = 15
b = 10
c = 20

print(a > b)    # True → because 15 > 10
print(a > c)    # False → because 15 is not greater than 20 

The output of the above code is shown below:

True
False 

Returns: True if greater, else False.

4. < (Less than)

The less than operator checks if the left value is smaller than the right value.

Example:

Python

a = 5
b = 10
c = 2

print(a < b)    # True → because 5 < 10
print(a < c)    # False → because 5 is not less than 2 

The output of the above code is shown below:

True
False 

Returns: True if smaller, else False.

5. >= (Greater than or equal to)

The greater than or equal to operator checks if the left value is greater than or equal to the right value.

Example:

Python

a = 10
b = 10
c = 5

print(a >= b)   # True → because 10 is equal to 10
print(a >= c)   # True → because 10 > 5
print(c >= a)   # False → because 5 is not >= 10 

The output of the above code is shown below:

True
True
False 

Returns: True if greater or equal, else False.

6. <= (Less than or equal to)

The less than or equal to operator checks if the left value is less than or equal to the right value.

Example:

Python

a = 10
b = 10
c = 15

print(a <= b)   # True → because 10 is equal to 10
print(a <= c)   # True → because 10 < 15
print(c <= a)   # False → because 15 is not <= 10 

The output of the above code is shown below:

True
True
False 

Returns: True if smaller or equal, else False.

Special Notes 1. Works with numbers, strings, and other data types.

Python

print("apple" == "apple")  # True
print("apple" < "banana")  # True (because 'a' < 'b') 

2. Used in conditions and loops:

Python

if a < b:
    print("a is smaller") 

3. Returns True/False which can be stored in variables:

Python

result = (a > b)
print(result)   # False