In Python, Comparison Operators (also known as Relational Operators) are used to compare two values or operands. The result of a comparison is always a Boolean value: either True or False.
These operators are the backbone of decision-making in programming, allowing you to control the flow of your logic based on specific conditions.
Comparison operators evaluate the relationship between two entities. In Python, you can compare numbers, strings, and even more complex data structures like lists or sets.
| Operator | Name | Description | Example (a=10,b=20) |
| == | Equal to | Returns True if operands are equal. | (a == b) is False |
| != | Not equal to | Returns True if operands are NOT equal. | (a != b) is True |
| > | Greater than | True if left is greater than right. | (a > b) is False |
| < | Less than | True if left is less than right. | (a < b) is True |
| >= | Greater than or equal to | True if left is greater than or equal to right. | (a >= b) is False |
| <= | Less than or equal to | True if left is less than or equal to right. | (a <= b) is True |
A common beginner mistake is using a single equals sign for comparison.
x = 5 assigns the value 5 to x.
x == 5 checks if x is equal to 5.
Python compares strings based on ASCII/Unicode values (lexicographical order).
Lowercase letters have higher values than uppercase letters (e.g., 'a' > 'A' is True).
Example: "apple" < "banana" is True because 'a' comes before 'b'.
Python allows you to chain multiple comparisons in a single expression, which is more readable than using logical operators.
Example: 5 < x < 10 is valid and checks if $x$ is between 5 and 10.
# Numerical Comparisons x = 10 y = 15 print(f"Is {x} equal to {y}? {x == y}") # False print(f"Is {x} not equal to {y}? {x != y}") # True print(f"Is {x} greater than {y}? {x > y}") # False print(f"Is {y} >= 15? {y >= 15}") # True # String Comparisons str1 = "Hello" str2 = "hello" print(f"Is '{str1}' == '{str2}'? {str1 == str2}") # False (Case-sensitive) # Chaining Example age = 25 is_eligible = 18 <= age <= 60 print(f"Is age {age} within range (18-60)? {is_eligible}") # True # Comparison with expressions print(f"Is 5 + 5 == 10? {5 + 5 == 10}") # True
Comparison operators are almost always used with if statements to execute specific blocks of code.
temperature = 30 if temperature > 25: print("It's a hot day!") else: print("The weather is pleasant.")
Copyright ©2025. All Rights Reserved Emblab THE RAVE INNOVATION