Comparison operators in Python are used to compare two values or expressions. These operators return a boolean value: True or False, depending on whether the comparison is valid or not.
Comparison Operators:
Equal to (==) – Checks if the two operands are equal.
x = 5y = 5
print(x == y) # Output: True
Not equal to (!=) – Checks if the two operands are not equal.
x = 5y = 3
print(x != y) # Output: True
Greater than (>) – Checks if the left operand is greater than the right operand.
x = 7y = 3
print(x > y) # Output: True
Less than (<) – Checks if the left operand is less than the right operand.
x = 4y = 10
print(x < y) # Output: True
Greater than or equal to (>=) – Checks if the left operand is greater than or equal to the right operand.
x = 5y = 5
print(x >= y) # Output: True
Less than or equal to (<=) – Checks if the left operand is less than or equal to the right operand.
x = 3y = 5
print(x <= y) # Output: True
Examples:
Example 1: Using all comparison operators
x = 10
y = 5
print(x == y) # Output: False
print(x != y) # Output: True
print(x > y) # Output: True
print(x < y) # Output: False
print(x >= y) # Output: True
print(x <= y) # Output: False
Example 2: Comparing strings
Python compares strings lexicographically (like dictionary order), based on their Unicode values.
str1 = "apple"
str2 = "banana"
print(str1 == str2) # Output: False
print(str1 != str2) # Output: True
print(str1 < str2) # Output: True (apple comes before banana)
print(str1 > str2) # Output: False
Example 3: Using comparison with boolean values
a = True
b = False
print(a == b) # Output: False
print(a != b) # Output: True
Key Points:
Comparison operators return a boolean result (True or False).
String comparison is done lexicographically, so "apple" is considered less than "banana".
You can use comparison operators with different data types like integers, floating-point numbers, strings, and booleans.
Let me know if you'd like more examples or a deeper explanation! 😊
0 Comments