Comparison Operators
Understanding Comparison Operators in Python
Comparison operators are essential tools for evaluating numeric conditions and making logical decisions in Python programming. They allow developers to compare values and create conditional logic with precision.
Standard Comparison Operators
Operator |
Description |
Example |
== |
Equal to |
5 == 5 |
!= |
Not equal to |
5 != 3 |
> |
Greater than |
10 > 5 |
< |
Less than |
3 < 7 |
>= |
Greater than or equal to |
5 >= 5 |
<= |
Less than or equal to |
4 <= 6 |
Practical Comparison Examples
def compare_numbers(a, b):
print(f"Comparison results for {a} and {b}:")
print(f"Equal to: {a == b}")
print(f"Not equal to: {a != b}")
print(f"Greater than: {a > b}")
print(f"Less than: {a < b}")
print(f"Greater than or equal to: {a >= b}")
print(f"Less than or equal to: {a <= b}")
## Example usage
compare_numbers(10, 5)
Chained Comparisons
def validate_range(value, min_val, max_val):
return min_val <= value <= max_val
## Example usage
print(validate_range(15, 10, 20)) ## True
print(validate_range(25, 10, 20)) ## False
Comparison Workflow
flowchart TD
A[Input Values] --> B{Compare Values}
B -->|Equal| C[Perform Equal Action]
B -->|Not Equal| D[Perform Unequal Action]
B -->|Greater| E[Perform Greater Action]
B -->|Less| F[Perform Less Action]
Advanced Comparison Techniques
Comparing Different Types
def safe_compare(a, b):
try:
return a == b
except TypeError:
return False
## Example usage
print(safe_compare(5, 5)) ## True
print(safe_compare(5, "5")) ## False
print(safe_compare(5, 5.0)) ## True
Floating-Point Comparison
import math
def float_compare(a, b, tolerance=1e-9):
return math.isclose(a, b, rel_tol=tolerance)
## Example usage
print(float_compare(0.1 + 0.2, 0.3)) ## True
print(float_compare(0.1 + 0.2, 0.4)) ## False
Key Considerations
- Use appropriate comparison operators for your specific use case
- Be cautious when comparing floating-point numbers
- Implement error handling for type mismatches
- Consider using
math.isclose()
for precise float comparisons
At LabEx, we recommend mastering comparison operators to write more robust and precise Python code.