Comparison Operators
Numbers or strings can be compared to each other using the following operators:
Comparison Operators | Meaning |
== | Equal To |
!= | Not Equal To |
< | Less Than |
<= | Less Than Or Equal To |
> | More Than |
>= | More Than Or Equal To |
Numbers are compared by magnitude.
Examples:
[code lang="python"]
>>> 789.36 > 56.0
True
>>> 45 == 456
False
>>> 5 != 4
True
[/code]
Strings comparison is done character by character, one after the other. Magnitude of characters is defined in the following ascending order: 0,1,...9,A,B,...Z,a,b,...z (lowercase letters last!). To be equal, strings should be of equal size and have all their characters equal. The relative magnitude of a string is determined by the relative magnitude of the first character that differs.
Examples:
[code lang="python"]
>>> 't' < 'a'
False
>>> 't' == 'T'
False
>>> 'tab' > 'TAB'
True
[/code]
Combining Comparisons
You can combine comparisons with the Boolean operators: and, or, not described in the following table.
Boolean Operators | Result |
X or Y | True if either X or Y is True False if both X and Y are False |
X and Y | True if both X and Y are True False if either X or Y is False |
not X | True if X is False False if X is True |
Just as you do in arithmetic operations, you can prioritise Boolean operations with brackets ():
[code lang="python"]
>>> ( a > 4 and b < 5 ) or b = 4
You can chain the comparisons together, for example:
>>> a=4
>>> 3<a<7 # equivalent to a>3 and a<7
True
[/code]