Comparing Values
You want to compare values with each other.
Use one of the comparison operators: <, >, <=], >=, ==, or !=.
Discussion
You use the < (less than) and > (greater than) operators in Recipe 6.15. Here’s the full set of comparison operators:
<
Less than
>
Greater than
<=
Less than or equal to
>=
Greater than or equal to
==
Exactly equal to
!=
Not equal to
Some people prefer to use the <> operator in place of !=. Both work the same.
You can test out these commands using the Python console (Recipe 5.3), as shown in the following exchange:
>>> 1 != 2 True >>> 1 != 1 False >>> 10 >= 10 True >>> 10 >= 11 False >>> 10 == 10 True >>> |
A common mistake is to use = (set a value) instead of == (double equals) in comparisons. This can be difficult to spot because if one half of the comparison is a variable, it is perfectly legal syntax and will run, but it will not produce the result you were expecting.
As well as comparing numbers, you can also compare strings using these comparison operators, for example:
>>> ‘aa’ < ‘ab’ True >>> ‘aaa’ < ‘aa’ False |
The strings are compared lexicographically—that is, in the order that you would find them in a dictionary.
This is not quite correct as, for each letter, the uppercase version of the letter is considered less than the lowercase equivalent.
See Also
See also Recipe 6.15.