Comparison Operators
Python · Operators
Theory
Comparison operators compare two values and always return a bool: == equal, != not equal, > greater, < less, >= greater or equal, <= less or equal. salary > 80000 evaluates to True or False, which you can store, print or use in an if. Python lets you chain them, so 1 < x < 10 means 1 < x and x < 10, with x evaluated only once.
How values compare depends on their type. Numbers compare by value across int and float (1 == 1.0 is True). Strings compare character by character using Unicode code points, so '10' < '9' is True and 'Z' < 'a' is True, a common trap with numbers stored as text. Different types are never equal ('5' == 5 is False), and ordering them raises TypeError (5 < 'a'). Never test floats with ==, because 0.1 + 0.2 == 0.3 is False.
Why we use it
Comparisons are the questions your code asks: is this salary high, is this date past due, does this ID match? Every filter, condition and validation rule starts with one.
When to use it
Use comparisons inside if, while, filters and list comprehensions. Convert text to numbers before comparing numeric data. For floats use math.isclose(); to check for None, use is None instead of == None.
How it works
- Python meets salary > 80000
- Evaluate both sides: 85000 and 80000
- Can these two types be ordered? Yes: Compare them by value. No: Raise TypeError (e.g. int vs str).
- Is the comparison true? Yes: Return True. No: Return False.
- print shows True
Syntax
== != > < >= <=Example
salary = 85000
print(salary > 80000)Key points
- == checks equality; = assigns, a common beginner mix-up
- Chainable in Python: 1 < x < 10
- Strings compare letter by letter: '10' < '9' is True
- '5' == 5 is False; 5 < 'a' raises TypeError
- Avoid == on floats: 0.1 + 0.2 == 0.3 is False