3. Comparison Operators
Comparison (also called Relational) Operators are used to compare two values or expressions. They return either True or False depending on the condition.
They are commonly used in conditional statements like if, while, etc. to make decisions based on comparisons.
List of Comparison Operators:
Operator | Name | Description | Example |
---|---|---|---|
== |
Equal to | Returns True if both values are equal |
5 == 5 → True |
!= |
Not equal to | Returns True if values are not equal |
5 != 3 → True |
> |
Greater than | Returns True if left value is greater |
7 > 9 → False |
< |
Less than | Returns True if left value is smaller |
3 < 6 → True |
>= |
Greater than or equal to | Returns True if left is greater or equal |
5 >= 5 → True |
<= |
Less than or equal to | Returns True if left is smaller or equal |
5 <= 3 → False |
Examples:
a = 10
b = 20
print(a == b) # False
print(a != b) # True
print(a > b) # False
print(a < b) # True
print(a >= b) # False
print(a <= b) # True
Note: Comparison always returns a boolean result — either True or False. These results help the program decide what to do next.
Using in If Statements
You can use comparison operators inside an if condition to check for a situation and perform an action accordingly.
age = 18
if age >= 18:
print("You are eligible to vote!")
else:
print("You are not eligible yet.")
In this example, the condition age >= 18 returns True or False, and based on that the respective message is printed.
Where it is Used?
- To compare numbers, strings, and variables
- Inside if-else or loops to make decisions
- Useful in sorting, filtering, validation, etc.
Summary
- == → Checks if two values are equal
- != → Checks if two values are not equal
- >, <, >=, <= → Used to compare values
- Returns: True or False
- Used in conditions like if-else, loops, decisions