 Introduction to Python : Comparison operators

# Comparison operators

Comparison operators compare two operands and return True or False based on the comparison.

Equality (==)

The equality operator is used to determine of two values or operands are equal. For example:

``print (2 == 2)``

will output True since 2 is indeed equal to 2 (in both type and value).

``print (4 == 5)``

will output False since 4 is obviously not equal to 5.

Inequality (!=)

The inequality operator is the opposite or the inverse of the equality operator. For example

``print (2 != 2)``

will output False while

``print (2 != 3) ``

will output True.

Less than (<) and greater than(>)

The less than operator (<) is used to check whether the left operand is less in value than the right operand while the greater than operator is used for the opposite (whether the left operand is greater in value than the right operand). For example

``print (2 < 3)``

will output True since 2 is rightly less than 3 while the opposite

``print (2 > 3) ``

will output False since 3 is rather greater than 2.

Less than or equal (<=) and greater than or equal (>=)

As the name implies, the less than or equal operator determines whether the left operand is less or equal in value that the right operand. Much the same way, the greater than or equal operator determines whether the left operand is greater or equal in value to the right operand. Examples:

``print (2 <= 4) ``

will output True. Similarly,

``print (4 <= 4)``

will also output True since 2 and 4 are less than and equal to 4 respectively.

In the reverse sense,

``````print (2 >= 4)
print (4 >= 4)``````

will output False and True respectively since 2 is not greater than 4 and 4 is equal to 4. ##### Introduction to Python
Number of sections:
11
Content length:
Delivery formats:
Introduction to Python