Python Comparison Operators
Comparison operators in Python are used to compare two values or expressions. The result of a comparison is always a Boolean value: either True
or False
.
List of Comparison Operators
Operator |
Description |
Example |
Result |
== |
Equal to |
5 == 5 |
True |
!= |
Not equal to |
5 != 3 |
True |
> |
Greater than |
7 > 3 |
True |
< |
Less than |
2 < 5 |
True |
>= |
Greater than or equal to |
5 >= 5 |
True |
<= |
Less than or equal to |
4 <= 2 |
False |
Detailed Explanation & Examples
1. Equal to (==
)
Checks if two values are equal.
a = 10
b = 10
print(a == b) # True, because 10 equals 10
c = "hello"
d = "Hello"
print(c == d) # False, string comparison is case-sensitive
2. Not Equal to (!=
)
Checks if two values are not equal.
x = 5
y = 3
print(x != y) # True, because 5 is not equal to 3
print(10 != 10) # False, both values are equal
3. Greater than (>
)
Returns True
if the left operand is greater than the right operand.
print(7 > 3) # True
print(3 > 7) # False
4. Less than (<
)
Returns True
if the left operand is less than the right operand.
print(2 < 5) # True
print(6 < 1) # False
5. Greater than or equal to (>=
)
Returns True
if the left operand is greater than or equal to the right operand.
print(5 >= 5) # True (equal)
print(7 >= 3) # True (greater)
print(2 >= 4) # False
6. Less than or equal to (<=
)
Returns True
if the left operand is less than or equal to the right operand.
print(4 <= 4) # True (equal)
print(3 <= 7) # True (less)
print(8 <= 2) # False
Using Comparison Operators in Conditions
Comparison operators are often used in conditional statements to control the program flow.
age = 20
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
Output:
You are an adult.
Combining Comparison Operators with Logical Operators
You can combine comparisons with logical operators (and
, or
, not
) to form more complex conditions.
score = 85
if score >= 50 and score <= 100:
print("You passed!")
else:
print("You failed!")
Summary
- Comparison operators compare two values.
- They return
True
or False
.
- They are essential for decision-making in programs.