Python Comparison Operators called Relational operators, and they are mostly used either in IF Statements or Python Loops. Comparison Operators in Python are usually used to check the relationship between two variables. If the relation is true, it returns TRUE, and if the relation is false, then it will return output as FALSE.
The below table shows all the Python Comparison Operators with examples.
Python Relational Operators | Usage | Description | Example |
---|---|---|---|
> | a > b | a is greater than b | 7 > 3 returns True (1) |
< | a < b | a is less than b | 7 < 3 returns False (0) |
>= | a >= b | a is greater than or equal to b | 7 >= 3 => True (1) |
<= | a <= b | a is less than or equal to b | 7 <= 3 return False (0) |
== | a == b | a is equal to b | 7 == 3 returns False (0) |
!= | a != b | a is not equal to b | 7 != 3 returns True(1) |
Python Comparison Operators Example
This example helps you to understand the Python Relational Operators practically. Here, we declared two variables a and b and their values are 9 and 4. Next, we are going to use these two variables to perform various comparison operations present in Python Programming
>>> a = 9 >>> b = 4 >>> print(" The Output of 9 > 4 is : ", a > b ) >>> print(" The Output of 9 < 4 is : ", a < b ) >>> print(" The Output of 9 <= 4 is : ", a <= b ) >>> print(" The Output of 9 >= 4 is : ", a >= b ) >>> print(" The Output of 9 Equal to 4 is : ", a == b ) >>> print(" The Output of 9 Not Equal To is : ", a != b )
We assigned 2 integer values a, b and we assigned the values 9 and 4.
>>> a = 9 >>> b = 4
In the next lines, We checked these values against each and every comparison operator (relational operator) present in Python Programming.
Use Python Comparison Operators in IF Statement
This example helps you to understand how Python Relational operators used in If statements. For this Python example, We use two variables x and y, and their values are 10 and 25.
Here, we are going to use these two variables in If Statement to check the conditions using one of the comparison operator present in python programming.
>>> x = 10 >>> y = 25 >>> if x >= y: print(" x value is Greater than or Equal to y ") else: print(" x value is Less than or Equal to y ")
In this Python realtional operator example, We assigned 2 integer values x, y, and assigned the values 10 and 25.
>>> x = 10 >>> y = 25
If Condition: If x is greater than or equal to y, then the first print statement will execute
print(" x value is Greater than or Equal to y ")
If the first condition fails, then the second print statement executes.
print(" x value is Less than or Equal to y ")
Here, 10 is neither greater nor equal to 25. So, the Second statement printed. Refer Python IF Statements and Python Loops.