Comparison or relational operators in Python are used to compare variables with values.
The comparison operator comes in between the left and right variables or operands. It simply tells us the relationship between the two.
Comparison operators in python include:
==
!=
>
<
>=
<=
Below is a table of all the comparison operators in Python.
In the table below, let’s say that x and y hold the values of 1 and 2, respectively.
Comparison Operator | Description | Example |
---|---|---|
== |
Equal to operator. This returns true only if the two operands are equal | x=y is not true because the value of x is not equal to y. |
!= |
Not equal to operator. This returns true if the two operands are not equal | x!=y is true because the value of x is not equal to y |
> |
Greater than operator. This returns true only if the value of the left operand is greater than that of the right operand | x>y is not true because the value of x is not greater than y |
< |
Less than operator. This returns true only if the value of the left operand is greater than that of the right operand | x<y is true because the value of x is less than the value of y |
>= |
Greater than or equal to operator. This returns true only if the value of the left operand is either greater or equal to that of the right operand | x>=y is not true because the value of x is neither greater or equal to y |
<= |
Less than or equal to operator. This returns true only if the value of the left operand is either lesser or equal to that of the right operand | x<=y is true because the value of x is lesser than the value of y |
Now let us write a code that will include all the comparison operators and tell us the relationship between the two operands.
# creating our variablesx = 1y = 2# Using the eqaul to comparison operatorif x == y:print('Line 1: x is equal to y')else:print('Line 1: x is not equal to y')# Using the not eqaul to comparison operatorif x != y:print('Line 2: x is not equal to y')else:print('Line 2: x is equxl to y')# Using the greater than comparison operatorif x > y:print('Line 3: x is greater than y')else:print('Line 3: x is not greater thab y')# Using the less than comparison operatorif x < y:print('Line 4: x is less than y')else:print('Line 4: x is not less than y')# Using the greater than or equal to comparison operatorif x >= y:print('Line 5: x is greater than or equal to y')else:print('Line 5: x is not greater than or equal to y')# Using the less than or equal to comparison operatorif x <= y:print('Line 6: x is lesser than or equal to y')else:print('Line 6: x is not lesser than or equal to y')