| Operator | Meaning | Example |
|---|---|---|
== | equal to | 2 == 2 |
!= | not equal to | 2 != 4 |
> | greater than | 4 > 2 |
>= | greater than or equal to | 4 >= 4 |
< | less than | 2 < 4 |
<= | less than or equal to | 2 <= 2 |
Equal (==)
Checks whether two values are equal.Not equal (!=)
Returns True when the two values are different.Greater than (>)
True if the left-hand operand is greater than the right-hand operand.Greater than or equal to (>=)
True if the left-hand operand is greater than or equal to the right-hand operand.Less than (<)
True if the left-hand operand is less than the right-hand operand.Less than or equal to (<=)
True if the left-hand operand is less than or equal to the right-hand operand.Comparison operators are most often used in conditional statements (for example,
if and while) to control program flow. They return True or False, which you can use directly in conditions. When comparing values, be mindful of types — comparing incompatible types may return False or raise a TypeError depending on the operation.Be careful when comparing different types (e.g., strings vs integers). For example,
"10" == 10 is False. Use explicit conversion (like int() or str()) when necessary to avoid unexpected results or runtime errors.Quick reference and common patterns
- Use equality (
==) to check for exact matches. - Use inequality (
!=) to exclude specific values. - Use chained comparisons for concise expressions:
0 < x < 10is valid and equivalent to(0 < x) and (x < 10). - Combine comparisons with logical operators (
and,or,not) to build complex conditions.