Previously we explored logical operators. This article introduces comparison operators — a separate category of operators used to compare values in Python. Comparison operators are fundamental for branching and looping (for example, in if and while statements) and return boolean results (True or False). There are six comparison operators in Python:Documentation Index
Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
Use this file to discover all available pages before exploring further.
| 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.